flutter 每次获取网络数据后都要setState刷新全局变量

import 'dart:convert';
import 'dart:ui';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'data/GetPullBlackList.dart';

/*
* 拉黑列表
*/
List<String> userId = ["0"];
List nickName = [0];
List avatar = [0];
//取屏幕最大宽度和高度
final width = window.physicalSize.width;
final height = window.physicalSize.height;

class PullBlackList extends StatefulWidget {
  const PullBlackList({key}) : super(key: key);

  @override
  //状态
  PullBlackListState createState() => PullBlackListState();
}

class PullBlackListState extends State<PullBlackList> {
  TextEditingController phoneController = TextEditingController();

  @override
  void initState() {
    // TODO: implement initState

    getPullBlackList();
    super.initState();
  }

  @override
  void dispose() {
    //销毁
    super.dispose();
  }

  @override
  void disposeClear() {
    userId.clear();
    super.dispose();
  }

  //获取拉黑列表接口
  getPullBlackList() async {
    var apiUrl = "http://47.242.63.216:9527/v1/blacklist/getList";

    SharedPreferences prefs = await SharedPreferences.getInstance();
    var tokens = prefs.getString("token");

    //参数
    Map map = {};
    //网络请求添加token请求头
    Response result = await Dio().post(apiUrl,
        data: map, options: Options(headers: {"x-token": tokens}));
    debugPrint("${result}");

    //json解析
    Map<String, dynamic> nickname = json.decode(result.toString());
    var httpRes = GetPullBlackList.fromJson(nickname);
    print("${httpRes.msg}和${httpRes.data.list1[0].userId}");
    //如果成功就吐司
    if (httpRes.code == 200) {
      Fluttertoast.showToast(
          msg: "${httpRes.msg}",
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.BOTTOM,
          timeInSecForIosWeb: 10,
          backgroundColor: Colors.white,
          textColor: Colors.black,
          fontSize: 16.0);
          
//成功后刷新数据
      setState(() {
        userId.clear();
        nickName.clear();
        avatar.clear();
        for (int i = 0; i < httpRes.data.list1.length; i++) {
          //如果数据是空的就清理掉,不显示
          if (httpRes.data.list1.length == 0) {
            disposeClear();
          } else {
            //有数据就添加
            userId.add(httpRes.data.list1[i].userId.toString());
            nickName.add(httpRes.data.list1[i].nickname);
            avatar.add(httpRes.data.list1[i].avatar);
          }
        }
      });
    }
  }

  @override
  Widget build(BuildContext context) {

    //显示拉黑列表的方法体
    Widget blackItem(String userId) {
      return Container(
          margin: EdgeInsets.only(top: 15, left: 15),
          child: Row(
            children: [
              Container(
                width: 75,
                height: 75,
                margin: const EdgeInsets.only(right: 18.0),
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(50),
                  image: const DecorationImage(
                    image: NetworkImage(
                        "https://www.itying.com/images/flutter/1.png"),
                    fit: BoxFit.cover,
                  ),
                ),
              ),
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Container(
                    margin: EdgeInsets.only(bottom: 8),
                    child: Text(
                      "Id: " + userId,
                      style: const TextStyle(
                        color: Color(0xFFCCCCCC),
                        fontSize: 16,
                      ),
                    ),
                  ),
                  Container(
                    child: Text(
                      "昵称: "+userId,
                      style: const TextStyle(
                        color: Color(0xFFCCCCCC),
                        fontSize: 16,
                      ),
                    ),
                  ),
                ],
              )
            ],
          ));
    }

    //拉黑列表
    Widget blackListSection = SizedBox(
      child: ListView(
        //解决ListView一定要设置高度才能显示问题
        shrinkWrap: true,
        physics: NeverScrollableScrollPhysics(),
        scrollDirection: Axis.vertical,
        children: userId.map((parameter) => blackItem(parameter)).toList(),
      ),
    );

    //MaterialApp-Scaffold
    return MaterialApp(
      //Scaffold相当于布局的容器
      home: Scaffold(
          appBar: AppBar(
            title: const Text('拉黑列表'),
            backgroundColor: const Color(0xFF222222),
            //文字居中
            centerTitle: true,
          ),
          //body就是写界面了
          body: Container(
        //设置界面背景
        decoration: const BoxDecoration(
          color: Color(0xFF222222),
        ),
        child: ListView(
          children: [
            blackListSection,
          ],
        ),
      )),
    );
  }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Flutter中,您可以使用以下方法定义全局变量: 1. 使用`final`或`const`关键字: 您可以在您的Dart文件中使用`final`或`const`关键字来定义全局变量。这些变量必须在声明时初始化,并且在整个应用程序中都是不可变的。 例如: ``` final String myGlobalVar = 'Hello World'; const int myGlobalNum = 42; ``` 2. 在`main.dart`文件中使用`static`关键字: 您可以在`main.dart`文件中使用`static`关键字来定义全局变量。这些变量可以在整个应用程序中访问,并且可以在运行时更改值。 例如: ``` void main() { MyApp.myGlobalVar = 'Hello World'; runApp(MyApp()); } class MyApp extends StatelessWidget { static String myGlobalVar; ... } ``` 3. 使用`Provider`或`GetX`等状态管理库: 您可以使用状态管理库(如`Provider`或`GetX`)来管理全局变量,并在整个应用程序中共享它们。 例如: ``` // Using Provider library void main() { runApp( ChangeNotifierProvider( create: (context) => MyGlobalVar(), child: MyApp(), ), ); } class MyGlobalVar extends ChangeNotifier { String myGlobalVar = 'Hello World'; void updateMyGlobalVar(String newValue) { myGlobalVar = newValue; notifyListeners(); } } class MyWidget extends StatelessWidget { @override Widget build(BuildContext context) { final myGlobalVar = Provider.of<MyGlobalVar>(context); return Text(myGlobalVar.myGlobalVar); } } // Using GetX library void main() => runApp(MyApp()); class MyGlobalVar extends GetxController { RxString myGlobalVar = 'Hello World'.obs; void updateMyGlobalVar(String newValue) { myGlobalVar.value = newValue; } } class MyWidget extends StatelessWidget { final MyGlobalVar myGlobalVar = Get.find(); @override Widget build(BuildContext context) { return Text(myGlobalVar.myGlobalVar.value); } } ``` 这些是定义全局变量的一些常见方法。根据您的应用程序需求和上下文选择合适的方法。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值