延迟初始化错误:字段'arquivo'尚未在flutter中初始化

1wnzp6jl  于 2023-03-31  发布在  Flutter
关注(0)|答案(1)|浏览(127)

当试图调用一个小部件时,它给出错误Field 'file' has not been initialized。
创建以下代码:

import 'dart:io';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:camera_camera/camera_camera.dart';
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:look_turismo_app/common/resources/app_colors.dart';
import 'package:look_turismo_app/common/resources/app_routes.dart';
import 'package:look_turismo_app/common/resources/app_strings.dart';
import 'package:look_turismo_app/features/places/presentation/widgets/favorite_list_item.dart';
import 'package:look_turismo_app/features/user/presentation/fragments/preview_page.dart';
import 'package:look_turismo_app/features/user/presentation/providers/user_provider.dart';
import 'package:look_turismo_app/features/user/presentation/widgets/anexo.dart';
import 'package:provider/provider.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:get/get.dart';

class ProfileFragment extends StatefulWidget {
  @override
  _ProfileFragmentState createState() => _ProfileFragmentState();
}

class _ProfileFragmentState extends State<ProfileFragment> {
  late File? arquivo;

  final GlobalKey<ScaffoldState> drawerscaffoldkey =
      new GlobalKey<ScaffoldState>();

  void _onTermsTap() async {
    final termsPdfUrl = Uri.encodeFull(
        'https://drive.google.com/file/d/1dFrlIRrm0JwJ9FN3cFmrmRJBlmgv8krH/view?usp=sharing');
    if (await canLaunch(termsPdfUrl)) {
      await launch(termsPdfUrl, enableJavaScript: true);
    } else {
      throw 'Could not launch $termsPdfUrl';
    }
  }

  showPreview(file) async {
    file = await Get.to(() => PreviewPage(file: file));

    if (file != null) {
      setState(() => arquivo = file);
      Get.back();
    }
  }

  Widget bottomSheet() {
    return Container(
      height: 100,
      width: MediaQuery.of(context).size.width,
      margin: EdgeInsets.symmetric(
        horizontal: 20,
        vertical: 20,
      ),
      child: Column(
        children: [
          Text(
            'Foto do Perfil',
            style: TextStyle(
              fontSize: 20,
            ),
          ),
          SizedBox(
            height: 20,
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              TextButton.icon(
                onPressed: () => Get.to(
                  () => CameraCamera(
                    onFile: (file) => showPreview(file),
                  ),
                ),
                icon: Icon(Icons.camera_alt_outlined),
                label: Text('Camera'),
              ),
              TextButton.icon(
                onPressed: () {},
                icon: Icon(Icons.image),
                label: Text('Galeria'),
              ),
            ],
          )
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Consumer<UserProvider>(
      builder: (context, provider, child) {
        return Scaffold(
          backgroundColor: AppColors.BACKGROUND_DARKER_COLOR,
          appBar: AppBar(
            backgroundColor: AppColors.BUTTON_PRIMARY_COLOR,
            centerTitle: true,
            leading: IconButton(
              onPressed: () {
                if (drawerscaffoldkey.currentState!.isDrawerOpen) {
                  Navigator.pop(context);
                } else {
                  drawerscaffoldkey.currentState?.openDrawer();
                }
              },
              icon: Icon(
                Icons.menu,
                size: 28,
              ),
            ),
          ),
          body: Scaffold(
            key: drawerscaffoldkey,
            drawer: Container(
              width: MediaQuery.of(context).size.width * 0.5,
              child: Drawer(
                child: Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: Column(
                    children: [
                      ListTile(
                        title: Text(
                          'Inicio',
                          style: TextStyle(
                              fontSize: 15,
                              fontFamily: GoogleFonts.lato().fontFamily),
                        ),
                        onTap: () {
                          Navigator.of(context).pushNamed(AppRoutes.HOME);
                        },
                      ),
                      ListTile(
                        title: Text(
                          'Perfil',
                          style: TextStyle(
                              fontSize: 15,
                              fontFamily: GoogleFonts.lato().fontFamily),
                        ),
                        onTap: () {
                          Navigator.of(context).pushNamed(AppRoutes.PROFILE);
                        },
                      ),
                      ListTile(
                        title: Text(
                          'Pesquisar',
                          style: TextStyle(
                              fontSize: 15,
                              fontFamily: GoogleFonts.lato().fontFamily),
                        ),
                        onTap: () {
                          Navigator.of(context).pushNamed(AppRoutes.EXPLORER);
                        },
                      ),
                      ListTile(
                        title: Text(
                          'Sair',
                          style: TextStyle(
                              fontSize: 15,
                              fontFamily: GoogleFonts.lato().fontFamily),
                        ),
                        onTap: () {
                          Navigator.of(context).pushNamed(AppRoutes.LOGIN);
                        },
                      ),
                    ],
                  ),
                ),
              ),
            ),
            body: Container(
              child: ListView(
                children: [
                  SizedBox(height: 16),
                  Container(
                    padding: EdgeInsets.symmetric(horizontal: 64, vertical: 32),
                    child: Stack(alignment: Alignment.center, children: [
                      arquivo != null
                          ? Anexo(arquivo: arquivo!)
                          : Container(
                              clipBehavior: Clip.antiAlias,
                              decoration: BoxDecoration(shape: BoxShape.circle),
                              child: CachedNetworkImage(
                                imageUrl: provider.loggedUser!.imageUrl,
                                width: 200,
                                height: 200,
                                fit: BoxFit.cover,
                              ),
                            ),
                      Positioned(
                        bottom: 0,
                        right: 70,
                        child: InkWell(
                          splashColor: Colors.transparent,
                          onTap: () {
                            showModalBottomSheet(
                                context: context,
                                builder: ((builder) => bottomSheet()));
                          },
                          child: Container(
                            height: 35,
                            width: 35,
                            decoration: BoxDecoration(
                              shape: BoxShape.circle,
                              border: Border.all(
                                width: 1,
                              ),
                              color: Colors.white,
                            ),
                            child: Icon(
                              Icons.camera_alt_outlined,
                            ),
                          ),
                        ),
                      ),
                    ]),
                  ),
                  Padding(
                    padding: const EdgeInsets.all(20),
                    child: Text(
                      AppStrings.MY_FAVORITES,
                      style: TextStyle(
                        fontSize: 16,
                        color: AppColors.PRIMARY_COLOR,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ),
                  provider.favorites.isEmpty
                      ? Container(
                          padding: EdgeInsets.only(left: 20),
                          child: Text(
                            AppStrings.NO_FAVORITES,
                          ),
                        )
                      : ListView.builder(
                          shrinkWrap: true,
                          padding: EdgeInsets.zero,
                          itemCount: provider.favorites.length,
                          itemBuilder: (context, index) => FavoriteListItem(
                              place: provider.favorites[index]),
                        ),
                  TextButton(
                    style: TextButton.styleFrom(
                      padding: EdgeInsets.symmetric(vertical: 24),
                    ),
                    child: Text(AppStrings.TERMS.toUpperCase()),
                    onPressed: () => _onTermsTap(),
                  ),
                ],
              ),
            ),
          ),
        );
      },
    );
  }
}

添加该部分时出现问题:

arquivo != null
                          ? Anexo(arquivo: arquivo!)
                          : Container(
                              clipBehavior: Clip.antiAlias,
                              decoration: BoxDecoration(shape: BoxShape.circle),
                              child: CachedNetworkImage(
                                imageUrl: provider.loggedUser!.imageUrl,
                                width: 200,
                                height: 200,
                                fit: BoxFit.cover,
                              ),
                            ),

它获取附加的小部件:

import 'dart:io';

import 'package:flutter/material.dart';

class Anexo extends StatelessWidget {
  final File arquivo;

  Anexo({Key? key, required this.arquivo}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      width: 200,
      height: 200,
      child: ClipRRect(
        borderRadius: BorderRadius.circular(20),
        child: Image.file(
          arquivo,
          fit: BoxFit.cover,
        ),
      ),
    );
  }
}

我需要一个附件小部件的变量文件在屏幕上增加时,它不是空的,否则用另一个字段填充它。

2wnc66cl

2wnc66cl1#

在初始化之前,你不能访问一个后期变量。在这里,构建方法在变量值被设置之前立即运行。
您需要做的就是删除变量之前的late

相关问题