【问题标题】:Update page data after pop Navigation Updated #5弹出导航更新后更新页面数据#5
【发布时间】:2020-08-26 16:49:11
【问题描述】:

我有页面导航到带有变量 (dID) 的第二页,如果它已更改,则等待返回相同的值,如果我没有做任何事情,则在第二页,如果我更改滑块,则该值必须返回而不做任何更改(dID) 的值必须增加 (1) ,但是当我 Navigate.pop 时返回值相同而不增加。

新更新:经过多次测试,问题出在第二页,当我更改滑块值时,我调用一个函数来获取新值(newSavedDayId),它是正确获取的,但只是在函数内部,滑块改变并获取新值后,返回null:

newSavedDayId  = Instance of 'Future<dynamic>'

返回值的第二页:

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import '../classes/viewdigree.dart';
import 'package:youtube_player_flutter/youtube_player_flutter.dart';
import 'package:shared_preferences/shared_preferences.dart';
class Days extends StatefulWidget {
  @override
  _DaysState createState() => _DaysState();
}
TextEditingController insertedDegree = TextEditingController();
class _DaysState extends State<Days> {
  @override
  Widget build(BuildContext context) {
    List digrees = [];
    var widthView = MediaQuery.of(context).size.width;
    Map rdata = ModalRoute.of(context).settings.arguments;
    var did = int.parse(rdata['dayId'].toString());
    var u_id = rdata['userID'];
    var m_id = rdata['courseId'];
    var lang = rdata['lang'];
    int w_id;
    var newSavedDayId = rdata['savedDayID']; ----// received value
    var username;
    if (did <= 6) {
      w_id = 1;
    } else if (did <= 12) {
      w_id = 2;
    } else if (did <= 18) {
      w_id = 3;
    } else {
      w_id = 4;
    }
    Future<List> fetchDigrees() async {
      var url =
          'https://srdtraining.com/api/controller/activities/activiy_list.php?d_id=$did&m_id=$m_id&u_id=$u_id';
      var response = await http.get(url);
      var data = jsonDecode(response.body);
      print(data);
      for (var x in data) {
        Digree newdigree = Digree(
            x['index'],
            x['title_k'],
            x['title_a'],
            x['aya'],
            x['link'],
            x['activity_k'],
            x['activity_a'],
            x['act_id'],
            x['mydigree']);
        digrees.add(newdigree);
      }
      return digrees;
    }
// Insert Func
    send_degree(uId, actId, degree, w_id, did, m_id) async {
      var sendData = {
        'u_id': uId.toString(),
        'act_id': actId.toString(),
        'digree': degree.toString(),
        'm_id': m_id.toString(),
        'd_id': did.toString(),
        'w_id': w_id.toString()
      };
      var url = 'https://srdtraining.com/api/controller/data/changedata.php';
      var response = await http.post(url, body: sendData);
    }
// End of Insert Func
//get user status .................. // this is the function to get new value
    void getUserStatus() async {
      SharedPreferences preferences = await SharedPreferences.getInstance();
      setState(() {
        username = preferences.getString('username');
      });
      var url =
          "http://srdtraining.com/api/controller/users/status_user.php?username=$username";
      var response = await http.get(url);
      var data = jsonDecode(response.body);
      setState(() {
        newSavedDayId = int.parse(data['d_id']); ----// Set New value by getting it from API after increasing by server.
      });

      print('newSavedDayId = $newSavedDayId');----// here it is print new value with increasing correctly
    }
// End get user
    return FutureBuilder(
        future: fetchDigrees(),
        builder: (context, snapshot) {
          if (snapshot.data == null) {
            return Scaffold(
              body: Container(
                decoration: BoxDecoration(
                    image: DecorationImage(
                        image: AssetImage('./assets/images/background.png'),
                        fit: BoxFit.cover)),
                child: Center(
                  child: Text("Loading"),
                ),
              ),
            );
          } else {
            YoutubePlayerController _controller = YoutubePlayerController(
                initialVideoId: snapshot.data[0].link,
                flags: YoutubePlayerFlags(
                  autoPlay: false,
                  mute: false,
                ));
            return Scaffold(
              appBar: AppBar(
                leading: IconButton(
                    icon: Icon(Icons.arrow_back),
                    onPressed: () {
                      Navigator.pop(context, newSavedDayId);
                    }),
                backgroundColor: Colors.pink[900],
                title: Text(
                  'ژیان و قورئان',
                  style: TextStyle(fontSize: 32),
                ),
                centerTitle: true,
              ),
              body: Container(
                decoration: BoxDecoration(
                    image: DecorationImage(
                        image: AssetImage('./assets/images/background.png'),
                        fit: BoxFit.cover)),
                height: MediaQuery.of(context).size.height,
                width: MediaQuery.of(context).size.width,
                child: ListView(
                  padding: EdgeInsets.fromLTRB(25, 20, 25, 20),
                  shrinkWrap: true,
                  children: <Widget>[
                    Text(
                        lang == 'k'
                            ? snapshot.data[0].title_k
                            : snapshot.data[0].title_a,
                        textAlign: TextAlign.center,
                        style: TextStyle(fontSize: 32, color: Colors.white)),
                    //for top margin
                    SizedBox(height: 20.0),
                    // dexription
                    Container(
                      padding: const EdgeInsets.all(15),
                      width: widthView,
                      decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(25),
                          color: const Color.fromRGBO(180, 80, 80, 0.3)),
                      child: Text(snapshot.data[0].aya,
                          textAlign: TextAlign.justify,
                          textDirection: TextDirection.rtl,
                          style: TextStyle(
                              fontFamily: 'Hafs',
                              fontSize: 26,
                              color: Colors.greenAccent[100])),
                    ),

                    // now populating your ListView for `Directionality`
                    Column(
                      children: <Widget>[
                        // Start activities
                        Column(
                            children: snapshot.data.map<Widget>((item) {
                          double _value =
                              double.parse(item.mydigree.toString());

                          return Directionality(
                            textDirection: TextDirection.rtl,
                            child: Column(
                              children: <Widget>[
                                Container(
                                  decoration: BoxDecoration(
                                      borderRadius: BorderRadius.circular(15),
                                      border: Border.all(
                                          width: 2, color: Colors.white),
                                      color:
                                          Color.fromRGBO(230, 200, 200, 0.2)),
                                  width: widthView,
                                  padding: EdgeInsets.all(25),
                                  margin: EdgeInsets.fromLTRB(0, 25, 0, 25),
                                  child: Column(
                                    children: <Widget>[
                                      Text(
                                        lang == 'k'
                                            ? item.activity_k
                                            : item.activity_a,
                                        textAlign: TextAlign.justify,
                                        style: TextStyle(
                                            fontSize: 28, color: Colors.white),
                                      ),
                                      SizedBox(
                                        height: 15,
                                      ),
                                      Container(
                                        decoration: BoxDecoration(
                                            boxShadow: [
                                              BoxShadow(
                                                color: Colors.yellow[200]
                                                    .withOpacity(0.2),
                                                spreadRadius: 2,
                                                blurRadius: 20,
                                              )
                                            ],
                                            borderRadius:
                                                BorderRadius.circular(15),
                                            color:
                                                Color.fromRGBO(0, 0, 0, 0.4)),
                                        width: widthView,
                                        padding: EdgeInsets.all(10),
                                        child: Slider(
                                            max: 100,
                                            min: 0,
                                            divisions: 100,
                                            value: _value,
                                            label: _value.round().toString(),
                                            onChanged: (val) {
                                              send_degree(u_id, item.act_id,
                                                  val, w_id, did, m_id);
                                            },
                                            onChangeEnd: (val) {
                                              setState(() {
                                                _value = val;
                                              });
                                              getUserStatus(); /// when i print the value here it is give me null
                                            }),
                                      ),
                                      SizedBox(
                                        height: 10,
                                      ),
                                      Text('$_value',
                                          style: TextStyle(
                                              fontSize: 26,
                                              color: Colors.white))
                                    ],
                                  ),
                                )
                              ],
                            ),
                          );
                        }).toList()),
                        // End activities
                        SizedBox(
                          height: 20,
                        ),
                        Text('خەلەکا ئەڤرو',
                            textAlign: TextAlign.right,
                            style:
                                TextStyle(fontSize: 26, color: Colors.yellow)),
                        SizedBox(
                          height: 20,
                        ),
                        YoutubePlayer(
                          controller: _controller,
                          showVideoProgressIndicator: true,
                          progressIndicatorColor: Colors.blueAccent,
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            );
          }
        });
  }
}

【问题讨论】:

    标签: flutter dart navigation reload


    【解决方案1】:

    您可以使用 ValueChanged onChanged 并回调您要更新的页面, 您可以在参数上传递 onChanged 函数, 当你改变你的价值使用:onChanged() 比在页面中你想看到在调用你的函数时设置状态的更新,

    【讨论】:

    • 谢谢姐姐,第三屏的level值改变了,我在pop Navigator上返回它的值,如上代码所示,但我无法接收它
    • 我不知道你是怎么做的,但是参考你的#update,因为你有正确的值,只是不知道如何传递它,尝试使用静态变量并在你的主类中调用它
    • 你能不能写代码更明白,谢谢姐姐
    • 放:静态 your_var;在更改值的类中,而不是调用它:YourClass.your_var
    • ex ;class MyClass 扩展 StatefulWidget { static int you_var; @override //代码 ; // 初始化你的静态变量 } ,而不是你调用 MyClass.your_var
    【解决方案2】:

    我通过将两个功能合二为一解决了这个问题:

    Future<List> fetchDigrees() async {
          var url =
              'https://srdtraining.com/api/controller/activities/activiy_list.php?d_id=$did&m_id=$m_id&u_id=$u_id';
          var response = await http.get(url);
          var data = jsonDecode(response.body);
          print(data);
          for (var x in data) {
            Digree newdigree = Digree(
                x['index'],
                x['title_k'],
                x['title_a'],
                x['aya'],
                x['link'],
                x['activity_k'],
                x['activity_a'],
                x['act_id'],
                x['mydigree']);
            digrees.add(newdigree);
          }
          return digrees;
        }
       void getUserStatus() async {
      SharedPreferences preferences = await SharedPreferences.getInstance();
      setState(() {
        username = preferences.getString('username');
      });
      var url =
          "http://srdtraining.com/api/controller/users/status_user.php?username=$username";
      var response = await http.get(url);
      var data = jsonDecode(response.body);
      setState(() {
        newSavedDayId = int.parse(data['d_id']); ----// Set New value by getting it from API after increasing by server.
      });
    

    他们现在喜欢这样并且工作正常:

    Future<List> fetchDigrees() async {
      SharedPreferences preferences = await SharedPreferences.getInstance();
      username = preferences.getString('username');
      var url1 =
          "http://srdtraining.com/api/controller/users/status_user.php?username=$username";
      var response1 = await http.get(url1);
      var data1 = jsonDecode(response1.body);
      newSavedDayId = int.parse(data1['d_id']);
      print('newSavedDayId before retrun = $newSavedDayId');
      var url =
          'https://srdtraining.com/api/controller/activities/activiy_list.php?d_id=$did&m_id=$m_id&u_id=$u_id';
      var response = await http.get(url);
      var data = jsonDecode(response.body);
      print(data);
      for (var x in data) {
        Digree newdigree = Digree(
            x['index'],
            x['title_k'],
            x['title_a'],
            x['aya'],
            x['link'],
            x['activity_k'],
            x['activity_a'],
            x['act_id'],
            x['mydigree']);
        digrees.add(newdigree);
      }
      return digrees;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-04-10
      • 1970-01-01
      • 2021-11-15
      • 1970-01-01
      • 2018-01-24
      • 2017-08-13
      • 2022-01-08
      相关资源
      最近更新 更多