Обновление данных страницы после обновления всплывающей навигации #5

#flutter #dart #navigation #reload

#flutter #dart #навигация #перезагрузите

Вопрос:

У меня есть страница перехода на вторую страницу с переменной (dID) с ожиданием возврата того же значения, если оно было изменено, на второй странице, если я ничего не делал, значение должно возвращаться без каких-либо изменений, если я изменил ползунок, значение (dID) должно увеличиваться на (1), но когда я перемещаюсь.pop, возвращаемое значение остается таким же без увеличения.

Новое обновление: после многих тестов, которые я выполнил, проблема на второй странице, когда я меняю значение ползунка, я вызываю функцию, чтобы получить новое значение (newSavedDayId), и она получает его правильно, но только внутри функции, после изменения ползунка и получения нового значения, оно возвращается к нулю :

 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=$didamp;m_id=$m_idamp;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,
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            );
          }
        });
  }
}
  

Ответ №1:

вы можете использовать измененное значение OnChanged и выполнить обратный вызов на страницу, которую хотите обновить, вы можете вставить функцию OnChanged в параметр, при изменении значения используйте : OnChanged(), чем на странице, на которой вы хотите увидеть обновление при вызове вашей функции с установленным состоянием ,

Комментарии:

1. Спасибо, сестра, значение level изменилось на третьем экране, и я возвращаю его значение в всплывающем навигаторе, как показано в кодах выше, но я не могу его получить

2. я не мог точно понять, как вы это делаете, но ссылаясь на ваш #update , поскольку у вас есть правильное значение и вы просто не знаете, как его передать, попробуйте использовать статическую переменную и вызвать ее в своем основном классе

3. Не могли бы вы написать код, чтобы лучше понять, спасибо, сестра

4. поместите : static your_var; в класс , который изменяет значение , чем вызывайте его : YourClass.your_var

5. например, класс MyClass расширяет StatefulWidget { static int you_var; @override //code ; // инициализирует вашу статическую переменную } , чем вы вызываете MyClass.your_var

Ответ №2:

Я решил это, объединив две функции в одну :

 Future<List> fetchDigrees() async {
      var url =
          'https://srdtraining.com/api/controller/activities/activiy_list.php?d_id=$didamp;m_id=$m_idamp;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=$didamp;m_id=$m_idamp;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;
}