How to call extractedUserData inside widget

Issue

I am working on login page, and I am using ShardPreferences I have brought my data to home page.
now I need that data inside it in widget.
I want to call extractedUserData inside widget which is stored value of json.decode.

class _HomeScreenState extends State<HomeScreen> {
  @override
  void initState() {
    super.initState();

    sf_extractedUserData();
  }

  Future<void> sf_extractedUserData() async {
    final pref = await SharedPreferences.getInstance();

    final extractedUserData = json.decode(pref.getString('userData') as String);
    print('HomeScreen :extractedUserData2' + extractedUserData.toString());
    print('extractedUserData uid: ' + extractedUserData['uid']);
    print('extractedUserData user_name: ' + extractedUserData['user_name']);
    print('extractedUserData user_email: ' + extractedUserData['user_email']);
    print('extractedUserData : ' + extractedUserData);
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Home"),
      ),
      body: Column(
        children: [
          Center(
              child: RaisedButton(
            onPressed: () {
              Navigator.of(context).pushReplacementNamed('/');
              Provider.of<Auth>(context, listen: false).logout();
            },
            shape:
                RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
            child: Text('logout'),
            color: Colors.green,
          )
              
              ),
        ],
      ),
    );
  }
}

Solution

First make your future function return String ‘extractedUserData’ then Use flutter’s Futurebuilder for this.

Future builder accepts an future argument and build the widget as soon as data arived.

Here is a example:-

return FutureBuilder(
  future: sf_extractedUserData(),
  builder: (context, response){
    return response.hasData ? Container(
          //Layout when data is returned by sf_extractedUserData
    ):
    Conatiner(
      //Layout when data is not returned yet
   );
  },
);

In this way you will be able to render your data inside the widget.

Also please stop calling SetState unnecessary its a powerful feature which also leads to many problems if used unnecessary.

and as always..
Happy Coding

Answered By – Abhay Kumar

Answer Checked By – Candace Johnson (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *