flutter

Flutter :how to call function in statelesswidget?


I want to show a list of data with list view and JSON. This code in a file with stateless widget. And this page opened after login. When I try in stateful widget, the code RUN normally. In stateless widget, when I debug it, the code didn't call function getData(). But directly went to

Widget build(BuildContext context) {    
     return new Scaffold( ... 

Here is complete code :

class frmClass extends StatelessWidget{
  List<dynamic> dta;
  get setState => null;

  Future<String> getData() async {
      var uri ='https://xxxx.com/class';
      var map = new Map<String, dynamic>();
      map["username"] = "abc";
      map["password"] = "1234";

      http.Response response = await http.post(
        uri,
        body: jsonEncode(map),
      );

      Map<String,dynamic> mp = jsonDecode(utf8.decode(response.bodyBytes));
      this.setState(() {
        dta = mp["data"];
        debugPrint(dta.toString());
      });

    }

  @override
  void initState(){
    this.getData();
  }

  @override
  Widget build(BuildContext context) {

     return new Scaffold(
       appBar: new AppBar(
           backgroundColor:Colors.transparent,
           elevation: 0.0,
           iconTheme: new IconThemeData(color: Color(0xFF18D191))),
       body: new ListView.builder(
           itemCount: dta == null ? 0 : dta.length,
           itemBuilder: (BuildContext context, int index){
             return new Card(
               child: new Text(dta[index]["className"]),
             );
           }
       ),
     );
  }
}

How can I fix it?


Solution

  • You can use a FutureBuilder to call getData() into build() method of StatelessWidget:

    https://api.flutter.dev/flutter/widgets/FutureBuilder-class.html

    But, this will fire getData() every time your statelessWidget is rebuild.

    Another way is to use reactive programing architecture (like Bloc, rxdart, etc..).

    Depends on what do you want, fire getData() every time or just once (or when your conditions are true/false).