[software development] 这段flutter怎么总是返回列表为空? Resolved
Tofloor
poster avatar
把一切操作变成GUI
deepin
Backbone of ecological co-construction group
2024-06-20 06:39
Author

lib/movie/list.dart

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

Dio dio = new Dio();

class MovieList extends StatefulWidget {
  MovieList({Key? key, required this.mt}) : super(key: key);
  final String mt;
  @override
  State createState() => _MovieListState();
}

class _MovieListState extends State {
  int page = 1;
  int pagesize = 10;
  var mlist = [];
  //控件被创建的时候执行这个函数
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getMovieList();
  }

  @override
  Widget build(BuildContext context) {
    // 确保mlist列表不为空,并且至少有一个元素
    if (mlist.isNotEmpty) {
      // 显示mlist列表中的第一个元素
      return Text("这是电影页面" + widget.mt + '${mlist[0]}');
    } else {
      // 如果mlist列表为空,显示一个默认消息
      return Text("这是电影页面" + widget.mt + '列表为空');
    }
  }

  getMovieList() async {
     print('开始测试打印...............................................');
    int offset = (page - 1) * pagesize;
    print('开始测试打印2...............................................');
    var response = await dio.get('https://httpbin.org/get');
    print('开始测试打印3...............................................');
    var result = response.data;
    var statusCode = response.statusCode;
    print('Status Code: $statusCode');

    // 检查响应状态码是否为200
    if (statusCode == 200) {
      // 调用setState方法来更新mlist的状态
      setState(() {
        mlist = result['origin'];
      });
      print('setstate结束');
    } else {
      print('Failed to fetch movie list: ${response.data}');
    }
    print('getMovieList结束');
  //   var result = response.data;
  //   var statusCode = response.statusCode;
   
  //   print('Status Code: $statusCode');
  //   // var co=response.data.
  //   // print('$result'+'-----------'+'$response');
  //   @override
  //   void setState(VoidCallback fn) {
  //     // TODO: implement setState
  //     super.setState((){
  //     mlist=result['origin'];
  //     // print('setstate结束');
  //     }     );
  //   }
  //   print('getMovieList结束');
  //   print('${mlist[0]}'); 
  // }
}
}

lib/main.dart

import 'package:flutter/material.dart';
import './movie/list.dart';
import 'package:dio/dio.dart';


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

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    //定义组件

    return MaterialApp(
        title: "SUPER",
        home: appa(),
        theme: ThemeData(primarySwatch: Colors.blue));
  }
} //MyApp

class appa extends StatelessWidget {
   appa({super.key});


  @override
  Widget build(BuildContext context) {
 
    return DefaultTabController(
        length: 3,
        child: Scaffold(
          appBar: AppBar(
            title: const Text("test项目"),
          ),
          drawer: Drawer(
            child: ListView(
              children: const [
                UserAccountsDrawerHeader(
                  accountName: Text("deepin"),
                  accountEmail: Text("[email protected]"),
                ),
                Divider(),
                ListTile(
                  title: Text('ListTile with red background'),
                  tileColor: Colors.red,
                  trailing: Icon(Icons.feed_sharp),
                ),
              ],
            ),
          ),
          bottomNavigationBar: Container(
            height: 48,
            decoration: const BoxDecoration(color: Colors.amberAccent),
            child: const TabBar(
              tabs: [
                Tab(
                  icon: Icon(Icons.movie_filter),
                  text: "正在热映",
                ),
                Tab(
                  icon: Icon(Icons.nearby_error_outlined),
                  text: "发现",
                ),
                Tab(
                  icon: Icon(Icons.people),
                  text: "我的",
                ),
              ],
            ),
          ),
          body:  TabBarView(children: [
            MovieList(mt:'a'),
            MovieList(mt:'b'),
            MovieList(mt:'c'),
          ]),
        ));
  }
}

接口返回的完整数据如下:




{
    "args": {},
    "headers": {
        "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
        "Accept-Encoding": "gzip, deflate, br, zstd",
        "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6",
        "Host": "httpbin.org",
        "Priority": "u=0, i",
        "Sec-Ch-Ua": "\"Microsoft Edge\";v=\"125\", \"Chromium\";v=\"125\", \"Not.A/Brand\";v=\"24\"",
        "Sec-Ch-Ua-Mobile": "?0",
        "Sec-Ch-Ua-Platform": "\"Windows\"",
        "Sec-Fetch-Dest": "document",
        "Sec-Fetch-Mode": "navigate",
        "Sec-Fetch-Site": "cross-site",
        "Sec-Fetch-User": "?1",
        "Upgrade-Insecure-Requests": "1",
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36 Edg/125.0.0.0",
        "X-Amzn-Trace-Id": "Root=1-66734d93-512d661d0f6d8bc47aa3cc52"
    },
    "origin": "154.201.95.43",
    "url": "https://httpbin.org/get"
}

为什么 mlist 一直都是为空?

Reply Favorite View the author
All Replies
BG7ZAG
deepin
2024-06-20 08:54
#1

StatelessWidget换成statefulWidget呢

Reply View the author
DebuggerX
deepin
2024-06-20 09:50
#2

接口返回的origin是个字符串,你直接赋值给一个数组变量就错误了啊:

image.png

这个接口根本就没有数组字段,目测你找错接口了。

看上去你是用 httpbin.org 模拟接口数据,那估计应该这么用:

image.png

另外建议还是多学学dart语法,比如

    if (mlist.isNotEmpty) {
      // 显示mlist列表中的第一个元素
      return Text("这是电影页面" + widget.mt + '${mlist[0]}');
    } else {
      // 如果mlist列表为空,显示一个默认消息
      return Text("这是电影页面" + widget.mt + '列表为空');
    }

其实更符合dart的写法只要一行:


  return Text("这是电影页面${widget.mt}${mlist.firstOrNull ?? '列表为空'}");
Reply View the author
fozei
deepin
2024-06-20 10:41
#3

result['origin']的值是字符串154.201.95.43,所以GG👼

Reply View the author
把一切操作变成GUI
deepin
Backbone of ecological co-construction group
2024-06-20 18:44
#4
DebuggerX

接口返回的origin是个字符串,你直接赋值给一个数组变量就错误了啊:

image.png

这个接口根本就没有数组字段,目测你找错接口了。

看上去你是用 httpbin.org 模拟接口数据,那估计应该这么用:

image.png

另外建议还是多学学dart语法,比如

    if (mlist.isNotEmpty) {
      // 显示mlist列表中的第一个元素
      return Text("这是电影页面" + widget.mt + '${mlist[0]}');
    } else {
      // 如果mlist列表为空,显示一个默认消息
      return Text("这是电影页面" + widget.mt + '列表为空');
    }

其实更符合dart的写法只要一行:


  return Text("这是电影页面${widget.mt}${mlist.firstOrNull ?? '列表为空'}");

是的,的确返回的是个字符串,

image.png

但是为什么你不用decode解析,直接用mlist取数组可以成功,而我却报error了?是因为你返回的movies是一个数组对吧,而只有一个值的情况下是不行的?


你这个是vscode吗?为什么我没有这么详细的报错提示?

Reply View the author
把一切操作变成GUI
deepin
Backbone of ecological co-construction group
2024-06-20 18:48
#5
fozei

result['origin']的值是字符串154.201.95.43,所以GG👼

为什么我看视频里面的都可以直接数组取值的?

Reply View the author