1

I'm following along on a flutter "World Clock" project, As I'm new to the flutter eco system i occasionally encounter errors.

Here's the way the logic is set up across the project.

The "Home" page pulls data from a "Loading" page that initializes the "Home Screen" with an instance of a object using the "Navigator.pushReplacementNamed" command.

I want to be able to create other instances of objects using a listbuilder on a "Choose" page using the "Navigator.pop" command. Unfortunately i get the error

*"Undefined name 'context'. (Documentation)Try correcting the name to one that is defined, or defining the name." *

Here's my code.

Choose Page -

    import 'package:flutter/material.dart';
    import 'package:world_time/services/world_time.dart';

   class ChooseLocation extends StatefulWidget {
      const ChooseLocation({Key? key}) : super(key: key);

      @override
      State<ChooseLocation> createState() => _ChooseLocationState();
    }
    List<WorldTime> locations = [
      WorldTime('Lagos', 'time', 'nigeria.png', 'Africa/Lagos', true),
      WorldTime('Islamabad', 'time', 'pakistan.png', 'Asia/Islamabad', true),
      WorldTime('Lund', 'time', 'sweden.png', 'Europe/Lund', true),
      WorldTime('Birmingham', 'time', 'uk.png', 'Europe/Birmingham', true),
      WorldTime('London', 'time', 'uk.png' , 'Europe/London', true),
      WorldTime('Athens', 'time', 'greece.png', 'Europe/Berlin', true),
      WorldTime('Cairo', 'time', 'egypt.png', 'Africa/Cairo', true),
      WorldTime('Nairobi', 'time', 'kenya.png', 'Africa/Nairobi', true),
      WorldTime('Chicago', 'time', 'usa.png', 'America/Chicago', true),
      WorldTime('New York', 'time', 'usa.png', 'America/New_York', true),
      WorldTime('Seoul', 'time', 'south_korea.png', 'Asia/Seoul', true),
      WorldTime('Jakarta', 'time', 'indonesia.png', 'Asia/Jakarta', true),
    ];

    void updateTime(index) async {
      WorldTime instance = locations[index];
      await instance.getTime();

**//The error is on the next line of code - (Undefined name 'context')**

      Navigator.pop(context, {
        'location': instance.location,
        'flag': instance.flag,
        'time': instance.time,
        'isDayTime': instance.isDayTime});
    }

    class _ChooseLocationState extends State<ChooseLocation> {
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            backgroundColor: Colors.blue[800],
            title: const Text('Choose A Location'),
            centerTitle: true,
            elevation: 0,
          ),
          body: ListView.builder(itemCount:locations.length,
          itemBuilder: (context, index){
            return Padding(
              padding: const EdgeInsets.symmetric(vertical: 1.0, horizontal: 4.0),
              child: Card(
                child: ListTile(
                  onTap: (){
                    updateTime(index);
                  },
                    title: Text(locations[index].location),
                  leading: CircleAvatar(
                    backgroundImage: AssetImage('assets/${locations[index].flag}'),
                  ),
                ),
              ),
            );
          }
          ),
        );
      }
    }


Loading Page -

    import 'package:flutter/material.dart';
    import 'package:world_time/services/world_time.dart';
    import 'package:flutter_spinkit/flutter_spinkit.dart';


    class Loading extends StatefulWidget {
      const Loading({Key? key}) : super(key: key);

      @override
      State<Loading> createState() => _LoadingState();
    }

    class _LoadingState extends State<Loading> {

      void setupWorldTime() async {
        WorldTime instance = WorldTime('Berlin', 'time', 'germany.png', 'Europe/Berlin', true);
        await instance.getTime();
        Navigator.pushReplacementNamed(context,'/home', arguments: {
          'location': instance.location,
          'flag': instance.flag, 
          'time': instance.time, 
          'isDayTime': instance.isDayTime
        });
      }

      @override
      void initState(){
        super.initState();
        setupWorldTime();
      }

      @override
      Widget build(BuildContext context) {
        return Scaffold(
          backgroundColor: Colors.lightBlue,
          body:Center(
          child: SpinKitFadingCircle(
          itemBuilder: (BuildContext context, int index) {
        return DecoratedBox(
        decoration: BoxDecoration(
        color: index.isEven ? Colors.white : Colors.lightBlue,
        ),
        );
        },
        ),
          ),
        );
      }
    }

Home Page -

    class Home extends StatefulWidget {
      const Home({Key? key}) : super(key: key);

      @override
      State<Home> createState() => _HomeState();
    }

    class _HomeState extends State<Home> {

      Map data = {};

      @override
      Widget build(BuildContext context) {

        data = data.isNotEmpty ? data : ModalRoute.of(context)?.settings.arguments as     Map<dynamic,dynamic>;
        print(data);

        String bgImage = (data?['isDayTime'] ?? false) ?'day.png' : 'night.png';
        Color bgColor = (data?['isDayTime'] ?? false) ? Colors.lightBlue : Colors.blue;

        return Scaffold(
          backgroundColor: bgColor,
          body: Container(
            decoration: BoxDecoration(
              image: DecorationImage(
                image: AssetImage('assets/$bgImage'),
                  fit:BoxFit.cover,
              ),
            ),
            child: Padding(
              padding: const EdgeInsets.fromLTRB(0,120,0,0),
              child: SafeArea(
                child: Column(
                  children: [
                TextButton.icon(onPressed: ()async {
                  dynamic result = await Navigator.pushNamed(context, '/location');
                  setState(() {
                    data = {
                      'time': result['time'],
                      'location': result['location'],
                      'isDayTime': result['isDayTime'],
                      'flag': result['flag']
                    };
                  });
                }, icon: const Icon(Icons.edit_location), label: const Text('Edit Location'),
                  style: TextButton.styleFrom(
                   foregroundColor: Colors.grey[300],
                  ),
                ),
                    SizedBox(height: 20.0),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Text(data['location'],
                          style: TextStyle(fontSize: 28, letterSpacing: 2, color: Colors.white),
                    ),
                      ],
                    ),
                    SizedBox(height: 20),
                    Text(data['time'],
                    style: TextStyle(fontSize: 66, color: Colors.white),
                    ),
                  ],
                ),
              ),
            ),
          ),
          );
      }
    }


I've tried ways to instantiate context but i'm not sure what data structure would work

1 Answers1

0

Navigator.pop(context, {}) is an event that needs to be triggered. Maybe by a button click like "close" or some other gesture like swiping. From what you've shared, it looks like you've defined the method in a state but are not actually using it. Move the logic into any button's onTap: () {Navigator.pop(context, {data});},

DARTender
  • 424
  • 2
  • 7
  • Also on the "Choose Page" the updateTime function calling Navigator.pop is called within and onTap button in the list view builder. Should i just delete method and pass the logic right into the onTap button. – HungerMadra Jan 09 '23 at 18:50
  • I eventually just did as @DARTender suggested and it worked. Commented out the function, moved the logic right into the onTap button as opposed to trying to call the method there. – HungerMadra Jan 10 '23 at 17:45
  • Glad I could be of assistance. – DARTender Jan 11 '23 at 22:07