Flutter FutureBuilder和颤振中的异步函数

Flutter FutureBuilder和颤振中的异步函数,flutter,Flutter,我有一个FutureBuilder的问题,它刷新并再次执行代码时,有一个变化,如当我改变单选按钮的值,我点击电台,它重新加载所有FutureBuilder它似乎。 编辑:我已经纠正了这个问题,这是我的解决方案,我不确定它是否一直有效 我的全部代码是: import 'package:flutter/material.dart'; import 'dart:convert'; import 'package:http/http.dart' as http; import 'dart:async';

我有一个FutureBuilder的问题,它刷新并再次执行代码时,有一个变化,如当我改变单选按钮的值,我点击电台,它重新加载所有FutureBuilder它似乎。 编辑:我已经纠正了这个问题,这是我的解决方案,我不确定它是否一直有效

我的全部代码是:

import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'dart:async';

// Create a Form widget.
class Affiche_grille extends StatefulWidget {
  @override
  _Affiche_grille_State createState() {
    return _Affiche_grille_State();
  }
}

// Create a corresponding State class.
// This class holds data related to the form.

class _Affiche_grille_State extends State<Affiche_grille> {
  @override
  final _formKey = GlobalKey<FormState>();
  List<String> radioValues = [];
  Future<List<Match>> grid;

  Future <List<Match>> Grille_display() async {
    // SERVER LOGIN API URL
    var url = 'http://www.axis-medias.fr/game_app/display_grid.php';

    // Store all data with Param Name.
    var data = {'id_grille': 1};

    // Starting Web API Call.
    var response = await http.post(url, body: json.encode(data));

    // Getting Server response into variable.

    var jsondata = json.decode(response.body);

    List<Match> Matchs = [];

    for (var u in jsondata) {
      Match match = Match(u["equipe1"],u["equipe2"],u["type_prono"]);
      Matchs.add(match);
      radioValues.add("N");
    }
    return Matchs;
  }

  void initState() {
    grid = Grille_display();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {

    final appTitle = 'MONEYFREE';

    return MaterialApp(
      title: appTitle,
      home: Scaffold(
        appBar: AppBar(
          title: Text(appTitle),
        ),
        body: Container(
          child:
            FutureBuilder(
              future: grid,
              builder: (BuildContext context, AsyncSnapshot snapshot) {
                if (snapshot.data == null) {
                  return Container (
                    child: Center(
                      child: Text("Chargement en cours...")
                    )
                  );
                }
                else {
                List<Match> values = snapshot.data;
                return Form(
                      key: _formKey,
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: <Widget>[
                          DataTable(
                            columnSpacing: 20,
                            columns: [
                              DataColumn(
                                label: Text("Libelle Match"),
                                numeric: false,
                                tooltip: "",
                              ),
                              DataColumn(
                                label: Text("1"),
                                numeric: false,
                                tooltip: "",
                              ),
                              DataColumn(
                                label: Text("N"),
                                numeric: false,
                                tooltip: "",
                              ),
                              DataColumn(
                                label: Text("2"),
                                numeric: false,
                                tooltip: "",
                              ),
                            ],
                            rows:
                            List.generate(values.length, (index) {
                              return DataRow(
                                  cells: [
                                    DataCell(
                                      Text(values[index].equipe1.toString() + " - " + values[index].equipe2.toString()),
                                    ),
                                    DataCell(
                                      Radio(
                                        value: "1",
                                        groupValue: radioValues[index],
                                        onChanged: (val) {
                                          setState(() {
                                            radioValues[index] = val;
                                            print('Change 1');
                                            print(radioValues);
                                          });
                                        },
                                      ),
                                    ),
                                    DataCell(
                                      Radio(
                                        value: "N",
                                        groupValue: radioValues[index],
                                        onChanged: (val) {
                                          setState(() {
                                            radioValues[index] = val;
                                            print('Change N');
                                            print(radioValues);
                                          });
                                        },
                                      ),
                                    ),
                                    DataCell(
                                      Radio(
                                        value: "2",
                                        groupValue: radioValues[index],
                                        onChanged: (val) {
                                          setState(() {
                                            radioValues[index] = val;
                                            print('Change 2');
                                            print(radioValues);
                                          });
                                        },
                                      ),
                                    ),
                                  ]
                              );
                            }).toList(),
                          ),
                          Center(
                            child: RaisedButton(
                              color: Colors.green,
                              textColor: Colors.white,
                              padding: EdgeInsets.fromLTRB(9, 9, 9, 9),
                              child: Text('VALIDER VOTRE GRILLE'),
                              onPressed: () {
                                Valide_grille();
                              },
                            ),
                          ),
                        ],
                      )
                  );
                };
                },
            ),
        ),
      ),
      );
  }

  Future Valide_grille() async{
    // For CircularProgressIndicator.
    bool visible = false ;
    // Showing CircularProgressIndicator.
    setState(() {
      visible = true ;
    });

    // SERVER LOGIN API URL
    var url = 'http://www.axis-medias.fr/game_app/valide_grid.php';

    var concatenate='';

    radioValues.forEach((item){
      concatenate=concatenate+item;
    });

    // Store all data with Param Name.
    var data = {'id_membre':1, 'id_grille':1,'result':concatenate};

    print (data);

    var grille_encode=jsonEncode(data);

    print(grille_encode);

    // Starting Web API Call.
    var response = await http.post(url, body: grille_encode);

    print(response.body);

    // Getting Server response into variable.
    var message = json.decode(response.body);

    // If the Response Message is Matched.
    if(message == 'OK')
    {
      print('VALIDATION DE LA GRILLE OK');
      // Hiding the CircularProgressIndicator.
      setState(() {
        visible = false;
      });

    }else{

      // If Email or Password did not Matched.
      // Hiding the CircularProgressIndicator.
      setState(() {
        visible = false;
      });

      // Showing Alert Dialog with Response JSON Message.
      showDialog(
        context: context,
        builder: (BuildContext context) {
          return AlertDialog(
            title: new Text(message),
            actions: <Widget>[
              FlatButton(
                child: new Text("OK"),
                onPressed: () {
                  Navigator.of(context).pop();
                },
              ),
            ],
          );
        },
      );
    }
  }
  }

class Match {

  final String equipe1;
  final String equipe2;
  final String typeprono;

  const Match(this.equipe1, this.equipe2, this.typeprono);

}
导入“包装:颤振/材料.省道”;
导入“dart:convert”;
将“package:http/http.dart”导入为http;
导入“dart:async”;
//创建一个表单小部件。
类Affiche\u扩展StatefulWidget{
@凌驾
_粘贴格栅状态createState(){
返回_Affiche_grill_State();
}
}
//创建相应的状态类。
//此类保存与表单相关的数据。
类(粘贴)(格栅)(状态)扩展状态{
@凌驾
final _formKey=GlobalKey();
列出radioValues=[];
未来电网;
Future grillu display()异步{
//服务器登录API URL
var url='1〕http://www.axis-medias.fr/game_app/display_grid.php';
//使用参数名称存储所有数据。
变量数据={'id_':1};
//正在启动Web API调用。
var response=wait http.post(url,body:json.encode(data));
//正在将服务器响应转换为变量。
var jsondata=json.decode(response.body);
列表匹配=[];
用于(jsondata中的变量u){
匹配匹配=匹配(u[“equipe1”]、u[“equipe2”]、u[“type_prono”]);
匹配。添加(匹配);
radioValues.添加(“N”);
}
返回匹配;
}
void initState(){
网格=网格显示();
super.initState();
}
@凌驾
小部件构建(构建上下文){
最终appTitle=‘免费’;
返回材料PP(
标题:appTitle,
家:脚手架(
appBar:appBar(
标题:文本(appTitle),
),
主体:容器(
儿童:
未来建设者(
未来:网格,
生成器:(BuildContext上下文,异步快照){
如果(snapshot.data==null){
返回容器(
儿童:中心(
子项:文本(“按课程收费…”)
)
);
}
否则{
列表值=snapshot.data;
报税表(
键:_formKey,
子:列(
crossAxisAlignment:crossAxisAlignment.start,
儿童:[
数据表(
柱间距:20,
栏目:[
数据列(
标签:文本(“诽谤匹配”),
数字:false,
工具提示:“”,
),
数据列(
标签:文本(“1”),
数字:false,
工具提示:“”,
),
数据列(
标签:文本(“N”),
数字:false,
工具提示:“”,
),
数据列(
标签:文本(“2”),
数字:false,
工具提示:“”,
),
],
排:
List.generate(values.length,(index){
返回数据行(
单元格:[
数据单元(
文本(值[index].equie1.toString()+“-”+值[index].equie2.toString()),
),
数据单元(
无线电(
值:“1”,
groupValue:radioValues[索引],
一旦更改:(val){
设置状态(){
放射性值[指数]=val;
打印(“更改1”);
打印(无线电值);
});
},
),
),
数据单元(
无线电(
值:“N”,
groupValue:radioValues[索引],
一旦更改:(val){
设置状态(){
放射性值[指数]=val;
打印(‘更改N’);
打印(无线电值);
});
},
),
),
数据单元(
无线电(
值:“2”,
groupValue:radioValues[索引],
一旦更改:(val){
设置状态(){
放射性值[指数]=val;
打印(“变更2”);
打印(无线电值);
});
},
),
),
Future _future;

@override
  void initState() {
    // TODO: implement initState
    _future = Grille_display();
  }
 ... 
 child: FutureBuilder(
            future: _future,  
import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'dart:async';

// Create a Form widget.
class Affiche_grille extends StatefulWidget {
  @override
  _Affiche_grille_State createState() {
    return _Affiche_grille_State();
  }
}

// Create a corresponding State class.
// This class holds data related to the form.

class _Affiche_grille_State extends State<Affiche_grille> {
  @override
  final _formKey = GlobalKey<FormState>();
  List<String> radioValues = [];

  Future<List<Match>> Grille_display() async {
    // SERVER LOGIN API URL
    var url = 'http://www.axis-medias.fr/game_app/display_grid.php';

    // Store all data with Param Name.
    var data = {'id_grille': 1};

    // Starting Web API Call.
    var response = await http.post(url, body: json.encode(data));

    // Getting Server response into variable.

    var jsondata = json.decode(response.body);

    List<Match> Matchs = [];

    for (var u in jsondata) {
      Match match = Match(u["equipe1"], u["equipe2"], u["type_prono"]);
      Matchs.add(match);
    }
    return Matchs;
  }

  Future _future;

  @override
  void initState() {
    // TODO: implement initState
    _future = Grille_display();
  }

  @override
  Widget build(BuildContext context) {
    final appTitle = 'MONEYFREE';

    return MaterialApp(
      title: appTitle,
      home: Scaffold(
        appBar: AppBar(
          title: Text(appTitle),
        ),
        body: Container(
          child: FutureBuilder(
            future: _future,
            builder: (BuildContext context, AsyncSnapshot snapshot) {
              if (snapshot.data == null) {
                return Container(
                    child: Center(child: Text("Chargement en cours...")));
              } else {
                List<Match> values = snapshot.data;
                values.forEach((m) {
                  radioValues.add("N");
                  //like N or something
                });
                print('valeur radio après initialisation');
                print(radioValues);
                return Form(
                    key: _formKey,
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[
                        DataTable(
                          columnSpacing: 20,
                          columns: [
                            DataColumn(
                              label: Text("Libelle Match"),
                              numeric: false,
                              tooltip: "",
                            ),
                            DataColumn(
                              label: Text("1"),
                              numeric: false,
                              tooltip: "",
                            ),
                            DataColumn(
                              label: Text("N"),
                              numeric: false,
                              tooltip: "",
                            ),
                            DataColumn(
                              label: Text("2"),
                              numeric: false,
                              tooltip: "",
                            ),
                          ],
                          rows: List.generate(values.length, (index) {
                            return DataRow(cells: [
                              DataCell(
                                Text(values[index].equipe1.toString() +
                                    " - " +
                                    values[index].equipe2.toString()),
                              ),
                              DataCell(
                                Radio(
                                  value: "1",
                                  groupValue: radioValues[index],
                                  onChanged: (val) {
                                    setState(() {
                                      radioValues[index] = val;
                                      print('Change 1');
                                      print(radioValues);
                                    });
                                  },
                                ),
                              ),
                              DataCell(
                                Radio(
                                  value: "N",
                                  groupValue: radioValues[index],
                                  onChanged: (val) {
                                    setState(() {
                                      radioValues[index] = val;
                                      print(radioValues);
                                    });
                                  },
                                ),
                              ),
                              DataCell(
                                Radio(
                                  value: "2",
                                  groupValue: radioValues[index],
                                  onChanged: (val) {
                                    setState(() {
                                      radioValues[index] = val;
                                      print(radioValues);
                                    });
                                  },
                                ),
                              ),
                            ]);
                          }).toList(),
                        ),
                        Center(
                          child: RaisedButton(
                            color: Colors.green,
                            textColor: Colors.white,
                            padding: EdgeInsets.fromLTRB(9, 9, 9, 9),
                            child: Text('VALIDER VOTRE GRILLE'),
                            onPressed: () {
                              Valide_grille();
                            },
                          ),
                        ),
                      ],
                    ));
              }
              ;
            },
          ),
        ),
      ),
    );
  }

  Future Valide_grille() async {
    // For CircularProgressIndicator.
    bool visible = false;
    // Showing CircularProgressIndicator.
    setState(() {
      visible = true;
    });

    // SERVER LOGIN API URL
    var url = 'http://www.axis-medias.fr/game_app/valide_grid.php';

    // Store all data with Param Name.
    var data = jsonEncode(radioValues);

    print(radioValues);
    // Starting Web API Call.
    var response = await http.post(url, body: json.encode(data));

    // Getting Server response into variable.
    var message = json.decode(response.body);

    // If the Response Message is Matched.
    if (message == 'OK') {
      print('VALIDATION DE LA GRILLE OK');
      // Hiding the CircularProgressIndicator.
      setState(() {
        visible = false;
      });
    } else {
      // If Email or Password did not Matched.
      // Hiding the CircularProgressIndicator.
      setState(() {
        visible = false;
      });

      // Showing Alert Dialog with Response JSON Message.
      showDialog(
        context: context,
        builder: (BuildContext context) {
          return AlertDialog(
            title: new Text(message),
            actions: <Widget>[
              FlatButton(
                child: new Text("OK"),
                onPressed: () {
                  Navigator.of(context).pop();
                },
              ),
            ],
          );
        },
      );
    }
  }
}

class Match {
  final String equipe1;
  final String equipe2;
  final String typeprono;

  const Match(this.equipe1, this.equipe2, this.typeprono);
}

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Affiche_grille(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}