php - 在刷卡器中从 php 加载图像时出现空错误

标签 php android flutter api dart

这是主页功能,我在其中为轮播图像添加了图像 slider (刷卡器),图像是从 PHP 网络加载的,但图像无法加载并抛出 null 错误,并且它的主体也已加载在下一个函数中,代码如下:

  class Home extends StatefulWidget {
    Home({
    Key? key,
    required this.body,
    }) : super(key: key);
    final body;

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

    class _HomeState extends State<Home> {
    Future<List<ModelEbook>>? getSlider;
    List<ModelEbook> listSlider = [];

    @override
    void initState() {
    super.initState();
    getSlider = fetchEbook(listSlider);
    }

    @override
    Widget build(BuildContext context) {
    return Container(
      child: SingleChildScrollView(
        child: FutureBuilder(
          future: getSlider,
          builder:
              (BuildContext context, AsyncSnapshot<List<ModelEbook>> snapshot) {
            if (snapshot.connectionState == ConnectionState.done) {
              //displays data here
              return Column(
                children: [
                  //Slider
                  // ImageSlider(),
                  Container(
                    child: FutureBuilder(
                      future: getSlider,
                      builder: (BuildContext context,
                          AsyncSnapshot<List<ModelEbook>> snapshot) {
                        if (snapshot.connectionState == ConnectionState.done) {
                          //Create design in here

                          return SizedBox(
                            height: 27.0.h,
                            child: Swiper(
                              autoplay: true,
                              itemCount: snapshot.data!.length,
                              itemBuilder: (BuildContext context, int index) {
                                // ModelEbook _ = snapshot.data![index];
                                return GestureDetector(
                                  onTap: () {},
                                  child: Padding(
                                    padding: EdgeInsets.all(10),
                                    child: Container(
                                      child: Stack(
                                        children: [
                                          ClipRRect(
                                            child: Image.network(
                                              listSlider[index].photo,
                                              fit: BoxFit.cover,
                                              width: 100.0.w,
                                            ),
                                            borderRadius:
                                                BorderRadius.circular(15),
                                          ),
                                        ],
                                      ),
                                    ),
                                  ),
                                );
                              },
                            ),
                          );
                        } else {
                          return Container();
                        }
                      },
                    ),
                  ),


                ],
              );
            } else if (snapshot.connectionState == ConnectionState.waiting) {
              return Center(child: CircularProgressIndicator());
            } else {
              print('error');
              return Text('error');
            }
          },
        ),
      ),
    );
这是上述函数的主体,其中我还添加了自定义应用栏和底部导航栏:
 class _HomeScreenState extends State<HomeScreen> {
     bool _folded = true;

     get currentIndex => null;

     @override
    Widget build(BuildContext context) {
      return Scaffold(
      body: AnimatedContainer(
        duration: Duration(milliseconds: 250),
        color: Colors.blueGrey.shade100,
        child: Column(
          children: [
            Row(
               mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                IconButton(
                  icon: SvgPicture.asset(
                    "assets/icons/menu.svg",
                  ),
                  onPressed: () {},
                ),
                Padding(
                  padding: const EdgeInsets.only(left: 110),
                  child: Container(
                    width: _folded ? 52 : 250,
                    height: getProportionateScreenHeight(50),
                    decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(32),
                        color: Colors.white,
                        boxShadow: [
                          BoxShadow(
                            color: Colors.brown.shade300.withOpacity(0.3),
                            spreadRadius: 0,
                            blurRadius: 8,
                            offset: Offset(-4, 0),
                          ),
                          BoxShadow(
                            color: Colors.grey.withOpacity(0.3),
                            spreadRadius: 0,
                            blurRadius: 8,
                            offset: Offset(4, 0),
                          ),
                          BoxShadow(
                            color: Colors.brown.shade300.withOpacity(0.3),
                            spreadRadius: 0,
                            blurRadius: 8,
                            offset: Offset(-4, 0),
                          ),
                          BoxShadow(
                            color: Colors.grey.withOpacity(0.3),
                            spreadRadius: 0,
                            blurRadius: 8,
                            offset: Offset(4, 0),
                          ),
                        ]),
                    child: Row(
                      children: [
                        Expanded(
                          child: Container(
                            padding: EdgeInsets.only(left: 16),
                            child: !_folded
                                ? TextField(
                                    decoration: InputDecoration(
                                      hintText: 'Search Book, Author,Genre ',
                                      hintStyle: TextStyle(
                                        color: Colors.black54,
                                        fontFamily:
                                            GoogleFonts.oregano().fontFamily,
                                      ),
                                      border: InputBorder.none,
                                    ),
                                  )
                                : null,
                          ),
                        ),
                        AnimatedContainer(
                          duration: Duration(milliseconds: 400),
                          child: Material(
                            type: MaterialType.transparency,
                            child: InkWell(
                                borderRadius: BorderRadius.only(
                                  topLeft: Radius.circular(_folded ? 32 : 0),
                                  topRight: Radius.circular(32),
                                  bottomLeft: Radius.circular(_folded ? 32 : 0),
                                  bottomRight: Radius.circular(32),
                                ),
                                child: Padding(
                                  padding: const EdgeInsets.all(16.0),
                                  child: SvgPicture.asset(
                                      _folded
                                          ? "assets/icons/search.svg"
                                          : "assets/icons/close.svg",
                                      height: getProportionateScreenHeight(18),
                                      color: Colors.black54),
                                ),
                                onTap: () {
                                  setState(() {
                                    _folded = !_folded;
                                  });
                                }),
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              ],
            ),
            
            Expanded(
              child: Home(
                body: currentIndex,
              ),
            ),
            Expanded(
              child: BottomDrawer(),
            ),
          
          ],
        ),
      ),
    );
  }
}
这是运行上述命令后显示的错误
enter image description here
这是运行上述命令后模拟器上显示的错误
enter image description here
Future<List<ModelEbook>> fetchEbook(List<ModelEbook> fetch) async 
    {
    print(
      "baseUrl ${ApiConstant().baseUrl + ApiConstant().api + 
    ApiConstant().latest}");
     var request = await Dio()
      .get(ApiConstant().baseUrl + ApiConstant().api + 
    ApiConstant().latest);

    for (Map<String, dynamic> ebook in request.data) {
    fetch.add(
      ModelEbook(
        id: ebook['id'],
        title: ebook['title'],
        photo: ebook['photo'],
        description: ebook['description'],
        catId: ebook['cat_id'],
        statusNews: ebook['status_newsNews'],
        pdf: ebook['pdf'],
        date: ebook['date'],
        authorName: ebook['author_name'],
        publisherName: ebook['publisher_name'],
        pages: ebook['pages'],
        language: ebook['language'],
        rating: ebook['rating'],
        free: ebook['free'], 
      ),
    );
    print("checkEbookFromDB ${ebook['photo']}");
    }
    return fetch;
    }

    class ApiConstant {
  String baseUrl = "http://i.p address(here)/ebookapp/";
  String api = "api.php?";
  String slider = "slider";
  String latest = "latest";

最佳答案

您无需调用两次 API 即可获取相同的数据,内部子节点使用父快照并关注 FutureBuilder结构体。在这种情况下调用future initState 不提供数据,您可以创建另一个async方法来处理,不过这个会很简单,不用initState

class _HomeState extends State<Home> {
  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: SingleChildScrollView(
        child: FutureBuilder(
          future: fetchEbook(),
          builder:
              (BuildContext context, AsyncSnapshot<List<ModelEbook>> snapshot) {
            if (snapshot.connectionState == ConnectionState.done &&
                snapshot.hasData) {
              //displays data here
              return Column(
                children: [
                  //Slider
                  // ImageSlider(),
                  Container(
                    child: SizedBox(
                      height: 27.0.h,
                      child: Swiper(
                        autoplay: true,
                        itemCount: snapshot.data!.length,
                        itemBuilder: (BuildContext context, int index) {
                          // ModelEbook _ = snapshot.data![index];
                          return GestureDetector(
                            onTap: () {},
                            child: Padding(
                              padding: EdgeInsets.all(10),
                              child: Container(
                                child: Stack(
                                  children: [
                                    ClipRRect(
                                      child: Image.network(
                                        snapshot.data![index].photo,
                                        fit: BoxFit.cover,
                                        width: 100.0.w,
                                      ),
                                      borderRadius: BorderRadius.circular(15),
                                    ),
                                  ],
                                ),
                              ),
                            ),
                          );
                        },
                      ),
                    ),
                  ),
                ],
              );
            } else if (snapshot.connectionState == ConnectionState.waiting) {
              return Center(child: CircularProgressIndicator());
            } else {
              print('error');
              return Text('error');
            }
          },
        ),
      ),
    );
  }
}

最好从 fetchEbook 返回可空列表因为不确定的 future 。
更多关于 FutureBuilder

关于php - 在刷卡器中从 php 加载图像时出现空错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70418010/

相关文章:

php - 将其连接到 wp_posts 时,如何将 wp_postmeta 表的所有值放在一行中?

php - 如何正确地要求 phar 文件

android - 如何重用已在 Navigation Drawer 上实例化的 fragment ?

android - 未创建 SQlite 表,但在 Android 中创建了数据库

android - Flutter:Android模拟器上未安装发布apk

javascript - 使用ajax将值从一个页面传递到另一个页面

javascript - 如何在脚本中 append PHP代码

java - 如何删除 TextInputLayout 提示文本中的省略号(三个点)?

android - Flutter Spotify API 认证

android - 在 flutter 中运行后台进程,当应用程序关闭时显示通知和点击 API,