如何在Flutter中发送POST API后刷新页面

3

我有一个POST API,当我发送请求时,在同一屏幕上给出GET API请求以显示JSON数据。发送信息后,GET数据未显示,必须注销后才能显示GET API数据。

如何在发送POST API数据后刷新页面,以便发送后显示信息。

POST API:

  void ladderAsli() async {
    if (_avgWeeklySales.text.isNotEmpty) {
      print(token);
      var response = await http.post(
          Uri.parse("localhost/backend/api/v1/pellekan/main/add/"),
          body: ({
            "avgWeeklySales": _avgWeeklySales.text,
          }),
          headers: {
            'Authorization': 'Bearer $token',
          });
      var body = jsonDecode(response.body);

      if (response.statusCode == 200) {
        SharedPreferences pref = await SharedPreferences.getInstance();
        ScaffoldMessenger.of(context)
            .showSnackBar(SnackBar(content: Text('${body['success']}')));
      } else {
        ScaffoldMessenger.of(context)
            .showSnackBar(SnackBar(content: Text('${body['error']}')));
      }
    } else {
      ScaffoldMessenger.of(context)
          .showSnackBar(SnackBar(content: Text('error')));
    }
  }

GET API:

  Future getDataLadder() async {
    print('bye');
    String token = await getToken();
    var response = await http.get(
        Uri.parse('localhost/backend/api/v1/pellekan/main/active'),
        headers: {
          'Content-type': 'application/json',
          'Accept': 'application/json',
          'Authorization': 'Bearer $token',
        });
    print('Token : ${token}');
    print('Response Body : ${response.body}');

    if (response.statusCode == 400) {
      var chieIN = jsonDecode(response.body);
      print("be moshkel khordim hich dataei nist");
    }
    if (response.statusCode == 200) {
      var chieIN = jsonDecode(response.body);
      // print('Hosssssein ' +
      //     chieIN['pellekanInfo']['pellekanPublishStatus'].toString());
      val = chieIN['pellekanInfo']['pellekanPublishStatus'].toString();
      print('BODOBA : ${val}');
      setState(() {
        val = '0';
      });
      //setState(() {
      // stringResponse = jsonDecode(response.body)['pellekan'];
      // val!.add(chieIN['pellekanInfo']['pellekanPublishStatus'].toString());
      stringResponse = [];
      stringResponse.addAll(List<NardebanData>.from(json
          .decode(response.body)['pellekan']
          .map((x) => NardebanData.fromJson(x))));
      print('String Response : ${stringResponse}');
      // nardeban_data = (stringResponse as List<NardebanData>).map((d) => NardebanData.fromJson(d)).toList();
      //});
    } else {
      print("error");
    }
  }

在`initState`函数中调用`getDataLadder()`方法。
刷新页面。
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:project/pattern_formatter.dart';
import 'package:project/screens/result-ladder.dart';
import 'package:http/http.dart' as http;
import 'package:shared_preferences/shared_preferences.dart';

List<NardebanData> nardeban_data = [];
List<NardebanData> stringResponse = [];

class Ladder extends StatefulWidget {
  const Ladder({Key? key}) : super(key: key);

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

Future<String> getToken() async {
  final SharedPreferences prefs = await SharedPreferences.getInstance();
  return prefs.getString('login')!;
}

class _LadderState extends State<Ladder> {
  bool value = true;
  String? val = "";

  String token = "";
  @override
  void initState() {
    super.initState();
    getDataLadder();
    getInfo();
  }

  void getInfo() async {
    SharedPreferences pref = await SharedPreferences.getInstance();

    setState(() {
      token = pref.getString("login")!;
    });
  }

  TextEditingController _avgWeeklySales = TextEditingController();
  TextEditingController _doubleSellingPricePercent = TextEditingController();
  TextEditingController _tripleSellingPricePercent = TextEditingController();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: Colors.white,
        body: Directionality(
            textDirection: TextDirection.rtl, child: gochgochApp()));
  }

  Future getDataLadder() async {
    print('bye');
    String token = await getToken();
    var response = await http.get(
        Uri.parse('localhost/backend/api/v1/pellekan/main/active'),
        headers: {
          'Content-type': 'application/json',
          'Accept': 'application/json',
          'Authorization': 'Bearer $token',
        });
    print('Token : ${token}');
    print('Response Body : ${response.body}');

    if (response.statusCode == 400) {
      var chieIN = jsonDecode(response.body);
      print("be moshkel khordim hich dataei nist");
    }
    if (response.statusCode == 200) {
      var chieIN = jsonDecode(response.body);
      // print('Hosssssein ' +
      //     chieIN['pellekanInfo']['pellekanPublishStatus'].toString());
      val = chieIN['pellekanInfo']['pellekanPublishStatus'].toString();
      print('BODOBA : ${val}');
      setState(() {
        val = '0';
      });
      //setState(() {
      // stringResponse = jsonDecode(response.body)['pellekan'];
      // val!.add(chieIN['pellekanInfo']['pellekanPublishStatus'].toString());
      stringResponse = [];
      stringResponse.addAll(List<NardebanData>.from(json
          .decode(response.body)['pellekan']
          .map((x) => NardebanData.fromJson(x))));
      print('String Response : ${stringResponse}');
      // nardeban_data = (stringResponse as List<NardebanData>).map((d) => NardebanData.fromJson(d)).toList();
      //});
    } else {
      print("hooooooooooooooooooooooooo");
    }
  }

  // Future asyncokeyeData() async {
  //   SharedPreferences pref = await SharedPreferences.getInstance();
  //   val = pref.getString('okeyeData');
  // }

  Widget gochgochApp() {
    print('Valiable : ${val}');
    if (val == '0') {
      print(val);
      // return Container(
      //   height: 200.0,
      //   child: Center(child: Text('شما در انتظار تایید نیست')),
      // );
      // return alertInForProcessLadder();

      return getBody();

      // return getBody();
    }
    // if (val == '2' || val == null) {
    //   return getForm();
    // }
    else {
      return getForm();
    }
  }

  Widget alertInForProcessLadder() {
    return (SafeArea(
      child: Padding(
          padding: EdgeInsets.symmetric(horizontal: 30, vertical: 24),
          child: SingleChildScrollView(
            child: Container(
              child: Center(
                  child: Text(
                      'شما یک پلکان اصلی در انتظار تایید ادمین دارید و نمی توانید پلکان دیگری ایجاد کنید')),
              height: 200.0,
            ),
          )),
    ));
  }

  Widget getForm() {
    return (SafeArea(
      child: Padding(
          padding: EdgeInsets.symmetric(horizontal: 30, vertical: 24),
          child: SingleChildScrollView(
            child: Column(
              children: [
                SizedBox(
                  height: 9,
                ),
                Text(
                  "فرم نردبان اصلی",
                  textAlign: TextAlign.center,
                  style: TextStyle(
                    fontSize: 18,
                    color: Colors.blue,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                SizedBox(
                  height: 10,
                ),
                Container(
                  padding: EdgeInsets.all(28),
                  decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(12),
                  ),
                  child: Column(
                    children: [
                      Text(
                        'مبلغ را به تومان وارد کنید',
                        textAlign: TextAlign.center,
                        style: TextStyle(
                          fontSize: 13,
                          color: Colors.black54,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                      SizedBox(
                        height: 4,
                      ),
                      TextField(
                        controller: _avgWeeklySales,
                        textAlign: TextAlign.center,
                        cursorColor: Colors.blue,
                        keyboardType: TextInputType.number,
                        inputFormatters: [ThousandsFormatter()],
                        decoration: InputDecoration(
                          hintStyle:
                              TextStyle(color: Colors.black26, fontSize: 13),
                          hintText: 'مثال : 1,000,000',
                          border: OutlineInputBorder(),
                          hintTextDirection: TextDirection.rtl,
                          contentPadding: EdgeInsets.all(8),
                        ),
                      ),
                      SizedBox(
                        height: 22,
                      ),
                      Text(
                        'درصد تخفیف برای 20 عدد',
                        textAlign: TextAlign.center,
                        style: TextStyle(
                          fontSize: 13,
                          color: Colors.black54,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                      SizedBox(
                        height: 4,
                      ),
                      TextField(
                        controller: _doubleSellingPricePercent,
                        textAlign: TextAlign.center,
                        cursorColor: Colors.blue,
                        keyboardType: TextInputType.number,
                        inputFormatters: [ThousandsFormatter()],
                        decoration: InputDecoration(
                          hintStyle:
                              TextStyle(color: Colors.black26, fontSize: 13),
                          hintText: 'مثال : 20',
                          border: OutlineInputBorder(),
                          hintTextDirection: TextDirection.rtl,
                          contentPadding: EdgeInsets.all(8),
                        ),
                      ),
                      SizedBox(
                        height: 22,
                      ),
                      Text(
                        'درصد تخفیف برای 30 عدد',
                        textAlign: TextAlign.center,
                        style: TextStyle(
                          fontSize: 13,
                          color: Colors.black54,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                      SizedBox(
                        height: 4,
                      ),
                      TextField(
                        controller: _tripleSellingPricePercent,
                        textAlign: TextAlign.center,
                        cursorColor: Colors.blue,
                        keyboardType: TextInputType.number,
                        inputFormatters: [ThousandsFormatter()],
                        decoration: InputDecoration(
                          hintStyle:
                              TextStyle(color: Colors.black26, fontSize: 13),
                          hintText: 'مثال : 30',
                          border: OutlineInputBorder(),
                          hintTextDirection: TextDirection.rtl,
                          contentPadding: EdgeInsets.all(8),
                        ),
                      ),
                      SizedBox(
                        height: 25,
                      ),
                      SizedBox(
                        width: double.infinity,
                        child: ElevatedButton(
                          onPressed: () {
                            ladderAsli();
                          },
                          style: ButtonStyle(
                            shape: MaterialStateProperty.all<
                                RoundedRectangleBorder>(
                              RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(15.0),
                              ),
                            ),
                            foregroundColor:
                                MaterialStateProperty.all<Color>(Colors.white),
                            backgroundColor:
                                MaterialStateProperty.all<Color>(Colors.blue),
                          ),
                          child: Padding(
                            child: Text(
                              'تایید',
                              style: TextStyle(
                                  fontWeight: FontWeight.bold, fontSize: 21),
                            ),
                            padding: EdgeInsets.all(15.0),
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          )),
    ));
  }

  Widget getBody() {
    var size = MediaQuery.of(context).size;
    return Container(
      width: size.width,
      height: size.height,
      decoration: BoxDecoration(
          borderRadius: BorderRadius.only(
              bottomLeft: Radius.circular(10),
              bottomRight: Radius.circular(10)),
          color: Colors.white),
      child: SingleChildScrollView(
        child: Column(
          children: [
            SizedBox(
              height: 10,
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Flexible(
                  child: Container(
                    height: 1,
                    decoration:
                        BoxDecoration(color: Colors.grey.withOpacity(0.2)),
                  ),
                ),
                SizedBox(
                  width: 10,
                ),
                buildHeader(
                  text: 'جهت فعال سازی پله 30 عددی فیلد زیر را فعال کنید',
                  child: buildSwitch(),
                ),
                SizedBox(
                  width: 10,
                ),
                Flexible(
                  child: Container(
                    height: 1,
                    decoration:
                        BoxDecoration(color: Colors.grey.withOpacity(0.2)),
                  ),
                ),
              ],
            ),
            SizedBox(
              height: 15,
            ),
            Column(
                children: List.generate(stringResponse.length, (index) {
              NardebanData dataItem = stringResponse[index];
              return Column(
                children: [
                  Padding(
                      padding: const EdgeInsets.only(right: 5, left: 5),
                      child: Container(
                        decoration: new BoxDecoration(
                          image: new DecorationImage(
                            image: new AssetImage("assets/images/bg.png"),
                            fit: BoxFit.fill,
                          ),
                        ),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Container(
                              height: 90,
                              // width: (size.width - 20) * 0.68,
                              child: Row(
                                children: [
                                  SizedBox(width: 20), // give it width
                                  Container(
                                      width: 60,
                                      decoration: BoxDecoration(
                                          color: Colors.blue,
                                          border:
                                              Border.all(color: Colors.blue),
                                          borderRadius:
                                              BorderRadius.circular(40.0)),
                                      child: Padding(
                                          padding: EdgeInsets.all(10.0),
                                          child: Text(dataItem.name!,
                                              textAlign: TextAlign.center,
                                              style: TextStyle(
                                                  fontSize: 12.5,
                                                  fontWeight: FontWeight.bold,
                                                  color: Colors.white)))),
                                  SizedBox(
                                    width: 10,
                                  ),
                                  Container(
                                    child: Column(
                                      mainAxisAlignment:
                                          MainAxisAlignment.center,
                                      crossAxisAlignment:
                                          CrossAxisAlignment.start,
                                      children: [
                                        Text(
                                          dataItem.form ?? '' + '',
                                          style: TextStyle(
                                              fontSize: 14,
                                              color: Colors.black54,
                                              fontWeight: FontWeight.w400),
                                          overflow: TextOverflow.ellipsis,
                                        ),
                                      ],
                                    ),
                                  ),
                                  Container(
                                    child: Column(
                                      mainAxisAlignment:
                                          MainAxisAlignment.center,
                                      crossAxisAlignment:
                                          CrossAxisAlignment.start,
                                      children: [
                                        Text(
                                          ' تا ' + dataItem.to!,
                                          style: TextStyle(
                                              fontSize: 14,
                                              color: Colors.black54,
                                              fontWeight: FontWeight.w400),
                                          overflow: TextOverflow.ellipsis,
                                        ),
                                      ],
                                    ),
                                  )
                                ],
                              ),
                            ),
                            Container(
                              width: (size.width - 120) * 0.32,
                              child: Row(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceBetween,
                                children: [
                                  Container(
                                    decoration: BoxDecoration(
                                        borderRadius: BorderRadius.circular(10),
                                        border: Border.all(color: Colors.blue)),
                                    child: Padding(
                                      padding: const EdgeInsets.only(
                                          right: 10,
                                          bottom: 4,
                                          left: 10,
                                          top: 4),
                                      child: Row(
                                        children: [
                                          SizedBox(
                                            width: 25,
                                            height: 25,
                                            child: TextField(
                                              textAlign: TextAlign.center,
                                              keyboardType:
                                                  TextInputType.number,
                                              decoration: InputDecoration(
                                                hintText: dataItem.percent!,
                                                border: InputBorder.none,
                                                contentPadding: EdgeInsets.only(
                                                  bottom: 8,
                                                  top: 3,
                                                ),
                                              ),
                                            ),
                                          )
                                        ],
                                      ),
                                    ),
                                  ),
                                  // Icon(
                                  //   Icons.notifications,
                                  //   size: 22,
                                  //   color: Colors.blue.withOpacity(0.7),
                                  // )
                                ],
                              ),
                            )
                          ],
                        ),
                      )),
                ],
              );
            })),
          ],
        ),
      ),
    );
  }

  Widget buildHeader({
    required Widget child,
    required String text,
  }) =>
      Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Text(
            text,
            style: TextStyle(fontSize: 14, fontWeight: FontWeight.bold),
          ),
          const SizedBox(height: 3),
          child,
        ],
      );

  Widget buildSwitch() => Transform.scale(
        scale: 2,
        child: Switch.adaptive(
          activeColor: Colors.blueAccent,
          activeTrackColor: Colors.blue.withOpacity(0.4),
          // inactiveThumbColor: Colors.orange,
          // inactiveTrackColor: Colors.black87,
          splashRadius: 50,
          value: value,
          onChanged: (value) => setState(() => this.value = value),
        ),
      );

  void ladderAsli() async {
    if (_avgWeeklySales.text.isNotEmpty) {
      print(token);
      var response = await http.post(
          Uri.parse("localhost/backend/api/v1/pellekan/main/add/"),
          body: ({
            "avgWeeklySales": _avgWeeklySales.text,
            "doubleSellingPricePercent": _doubleSellingPricePercent.text,
            "tripleSellingPricePercent": _tripleSellingPricePercent.text,
          }),
          headers: {
            'Authorization': 'Bearer $token',
          });
      var body = jsonDecode(response.body);

      if (response.statusCode == 200) {
        SharedPreferences pref = await SharedPreferences.getInstance();
        ScaffoldMessenger.of(context)
            .showSnackBar(SnackBar(content: Text('${body['success']}')));
      } else {
        ScaffoldMessenger.of(context)
            .showSnackBar(SnackBar(content: Text('${body['error']}')));
      }
    } else {
      ScaffoldMessenger.of(context)
          .showSnackBar(SnackBar(content: Text('مبلغ کل را وارد کنید')));
    }
  }
}

这是 JSON 示例:

{
    "pellekan": [
        {
            "name": "پله 1",
            "form": null,
            "to": "9999",
            "percent": 1
        },
        {
            "name": "پله 2",
            "form": "9999",
            "to": 10.74,
            "percent": 2.89
        },
        {
    ]
}

@lava 什么是主页小部件? 在 setState 中,我使用 SharedPreference 设置了令牌和一个值。 - Sara
抱歉,您的页面需要刷新。我认为您可以使用setState或其他状态管理工具来解决这个问题。我认为您首先需要在第一次加载页面时获取JSON数据,然后在单击按钮以发布某些值时立即进行请求并使用最新数据更新UI。是这样吗? - lava
@lava 是的,我想要那个。 - Sara
@lava,我已经添加了你的请求。 - Sara
@lava 为什么不回答我的问题?:( - Sara
显示剩余3条评论
2个回答

0

enter image description here

Listview.builder小部件用于传播UI中的更改

ListView.builder(
                itemCount: datajson!.length,
                itemBuilder: (context, index) {
                  return Text(datajson![index].toString(),
                      style: TextStyle(fontSize: 10));
                })

在这里,我使用示例的POST和GET方法,结合延迟等待来模拟API等待并提供数据。

void MygetData() {
    Future.delayed(Duration(seconds: 3), () {
      setState(() {
        isloading = false;

        datajson;
      });
    });
  }
  void posts() {
    Future.delayed(Duration(seconds: 3), () {
      // other post request

      datajson?.add({"name": "2"});
      MygetData();
    });
  }

示例代码 dartpad live

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();

  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

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

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

int myvalue = 0;
List<Map<String, dynamic>>? datajson = [];

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

  bool isloading = false;

  @override
  void initState() {
    isloading = true;

    Future.delayed(Duration(seconds: 3), () {
      setState(() {
        datajson?.add({"name": "1"});
        isloading = false;
      });
    });
  }

  void MygetData() {
    Future.delayed(Duration(seconds: 3), () {
      setState(() {
        isloading = false;

        datajson;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: Column(
// shrinkWrap: true,
        children: [
          Container(
            height: 45,
            child: ElevatedButton(
                onPressed: () {
                  setState(() {
                    isloading = true;
                  });

                  posts();
                },
                child: Text(
                  "Post",
                  style: TextStyle(fontSize: 10),
                )),
          ),
          Expanded(
            child: ListView.builder(
                itemCount: datajson!.length,
                itemBuilder: (context, index) {
                  return Text(datajson![index].toString(),
                      style: TextStyle(fontSize: 10));
                }),
          ),
          isloading
              ? Container(
                  height: 50,
                  width: 50,
                  child: CircularProgressIndicator(),
                )
              : Text("")
        ],
      ),
    );
  }

  void posts() {
    Future.delayed(Duration(seconds: 3), () {
      // other post request

      datajson?.add({"name": "2"});
      MygetData();
    });
  }
}

我不使用Listview.builder,我将所有代码添加到答案中,请在我的代码中进行编辑。 - Sara
请在问题中添加您的示例 JSON,请删除您的答案(如果有)并将其添加到问题本身中。 - lava
我在问题中添加了JSON Simple,如果你抄袭我的代码回答,我会删除回答。 - Sara

0

我认为解决这个问题的最佳和最简单的方法是:

Navigator.push(context,MaterialPageRoute(builder: (context) =>yourclass()));

但你应该在initstate中像这样获取数据。

 void initState() {    fetchYourItems();      super.initState();  };

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接