Home > Mobile >  Why can't I use variable in Text Widget flutter
Why can't I use variable in Text Widget flutter

Time:05-24

Finally with some fantastic help I got the variables I need, but the question now is why can't I use them further in a text Widget, breaking my head over it. Everything is working except accessing the variables at the place I need them. It prints the variable just fine.

I simplified the code, just accessing the first map of a json list:

 @override
    Widget build(BuildContext context) {
    return Scaffold(
     backgroundColor: Colors.black,
     body: FutureBuilder(
      future: Future.wait([fetchList(), fetchMap()]),
      builder: (context, snapshot) {
         if (snapshot.hasData) {
         print("snapshot has data");
         ////list json variables
         final dp = (snapshot.data as List)[0] as List<dynamic>;
         final first = dp[0];
         final dpid1 = first["id"]; //1
         final dpbme1 = first["name"];
         print(dpbme1);
.......................etcetera................
        } else if (snapshot.hasError) {
         return Text('${snapshot.error}');
         }
         
        return SafeArea(
          child: SingleChildScrollView(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: <Widget>[
                Image.asset('assets/images/top_logo_320x40.jpg'),
                Center(child: Text('$dpbme1',      <<<<<gives an error 'undefined name'
                  style:   TextStyle(..........etcetera...................

If someone could please help me showing how to do it, I am grateful.

Thank you.

CodePudding user response:

When you declared dpbme1 you did so within the scope of an if-statement block. Once that if-statement is over, any variables declared within the block go out of scope - meaning neither the name, nor the value is defined any longer.

If you want your variables to persist beyond the scope of the if-statement, you'll need to declare them before it, or return the widget before the if-statement closes:

if (snapshot.hasData) {
  // Your declarations here...

  return SafeArea(
    // Snip
  );
}

CodePudding user response:

you need to return the widget in the if statement that assigned the variable.

  • Related