【问题标题】:image asset not loading in flutter firebase project图像资产未加载到颤振 Firebase 项目中
【发布时间】:2020-04-10 17:31:45
【问题描述】:

我正在关注一个关于颤振的教程,我正在尝试加载图像,不幸的是,图像无法加载。我总是在控制台中出现无法加载图像的错误。我的代码如下:

import 'dart:ffi';

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


final GoogleSignIn googleSignIn = new GoogleSignIn();

class Home extends StatefulWidget {
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {
  bool isAuth = false;
  @override
  Void initState() {
    super.initState();
    //detect when user sign in
    googleSignIn.onCurrentUserChanged.listen((account) {
     handleSignIn(account);
    }, onError:(err){
      print('error signing in:$err');
    }

    );
    //re-authenticated when user sign in the app
    googleSignIn.signInSilently(suppressErrors: false).then((account){
         handleSignIn(account);

    }).catchError((err){
       print('error signing in:$err');
    });
  }

  handleSignIn(GoogleSignInAccount account){
        if (account != null) {
        print(account);
        setState(() {
          isAuth = true;
        });
      } else {
        setState(() {
          isAuth = false;
        });
      }
  }

  login() {
    googleSignIn.signIn();
  }

  logOut(){

    googleSignIn.signOut();
  }

  Widget buildAuthScreen() {
    return RaisedButton(
      child:Text("LogOut"),
    onPressed: (){
       logOut();
    },
    );
  }

  Scaffold unAuthBuildScreen() {
    return Scaffold(
      body: Container(
        decoration: BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topRight,
            end: Alignment.bottomLeft,
            colors: [
              Theme.of(context).primaryColor,
              Theme.of(context).accentColor,
            ],
          ),
        ),
        alignment: Alignment.center,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            Text(
              "FlutterShare",
              style: TextStyle(
                //fontFamily: "Signatra",
                fontSize: 50.0,
                color: Colors.white,
              ),
            ),
            GestureDetector(
              onTap: () => print("tapped"),
              child: Container(
                width: 260.0,
                height: 60.0,
                decoration: BoxDecoration(
                  image: DecorationImage(
                  // image:AssetImage(bund"assets/images/google_sigin_button.png"),
                  image: AssetImage("assets/images/google_sigin_button.png"),
                     fit: BoxFit.fill),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return isAuth ? buildAuthScreen() : unAuthBuildScreen();
  }
}

pubspec.yaml如下,请帮帮我

name: fluttershare
description: A new Flutter project.

# The following defines the version and build number for your application.
# A version number is three numbers separated by dots, like 1.2.43
# followed by an optional build number separated by a +.
# Both the version and the builder number may be overridden in flutter
# build by specifying --build-name and --build-number, respectively.
# In Android, build-name is used as versionName while build-number used as versionCode.
# Read more about Android versioning at https://developer.android.com/studio/publish/versioning
# In iOS, build-name is used as CFBundleShortVersionString while build-number used as CFBundleVersion.
# Read more about iOS versioning at
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
version: 1.0.0+1

environment:
  sdk: ">=2.1.0 <3.0.0"

dependencies:
  flutter:
    sdk: flutter
  firebase_auth: ^0.15.5+3
  firebase_database: ^3.1.3
  cloud_firestore: ^0.13.4+1
  image_picker: ^0.6.4
  firebase_storage: ^3.1.5
  google_sign_in: ^4.4.1
  geolocator: ^5.3.1
  uuid: ^2.0.4
  timeago: ^2.0.26
  path_provider: ^1.6.4
  flutter_svg:
  cached_network_image: ^2.0.0
  firebase_messaging: ^6.0.13
  image: ^2.1.4
  animator: ^1.0.0+5


  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^0.1.2

dev_dependencies:
  flutter_test:
    sdk: flutter


# For information on the generic Dart part of this file, see the
# following page: https://dart.dev/tools/pub/pubspec

# The following section is specific to Flutter.
flutter:
  uses-material-design: true
  assets:
    - assets/images/google_signin_button.png
    - assets/images/upload.svg
    - assets/images/search.svg
    - assets/images/activity_feed.svg
    - assets/images/no_content.svg
  # An image asset can refer to one or more resolution-specific "variants", see
  # https://flutter.dev/assets-and-images/#resolution-aware.

  # For details regarding adding assets from package dependencies, see
  # https://flutter.dev/assets-and-images/#from-packages

  # To add custom fonts to your application, add a fonts section here,
  # in this "flutter" section. Each entry in this list should have a
  # "family" key with the font family name, and a "fonts" key with a
  # list giving the asset and other descriptors for the font. For
  # example:
  # fonts:
  #   - family: Schyler
  #     fonts:
  #       - asset: fonts/Schyler-Regular.ttf
  #       - asset: fonts/Schyler-Italic.ttf
  #         style: italic
  #   - family: Trajan Pro
  #     fonts:
  #       - asset: fonts/TrajanPro.ttf
  #       - asset: fonts/TrajanPro_Bold.ttf
  #         weight: 700
  #
  # For details regarding fonts from package dependencies,
  # see https://flutter.dev/custom-fonts/#from-packages

请帮助我过去 3 天一直在处理这个问题

【问题讨论】:

  • 发布您遇到的错误
  • 您好 mt4real,请输入您的错误和 pubspec 文件
  • 这是我的 pubspec.yaml 我尝试了不同的职位名称:fluttershare 描述:一个新的 Flutter 项目。颤振:使用材料设计:真实资产:-资产/图像/google_signin_button.png-资产/图像/upload.svg-资产/图像/搜索.svg-资产/图像/activity_feed.svg-资产/图像/no_content。 svg
  • @mt4real 我已经用更多细节编辑了我的答案。希望它能帮助您解决问题。

标签: flutter


【解决方案1】:

这是 Android 的密度与 Flutter 像素比

Android density qualifier   Flutter pixel ratio
   ldpi                         0.75x
   mdpi                         1.0x
   hdpi                         1.5x
   xhdpi                        2.0x
   xxhdpi                       3.0x
   xxxhdpi                      4.0x

添加图片的最佳方式是创建一个类似的资产目录结构。

将基于密度映射的图像放到适当的文件夹中,flutter 将根据设备密度选择图像。

您不需要在pubspec.yaml 中添加每个图像路径,仅根文件夹就足够了。确保assetspubspec.yaml 位于同一目录级别。

flutter:
  assets:
    - assets/images/

希望它能解决你的问题。

【讨论】:

    【解决方案2】:

    我认为如果您使用 firebase 进行身份验证,您应该使用 firebase 存储来存储您的图像。

    您需要这些导入。

    import 'package:firebase_storage/firebase_storage.dart';
    import 'package:firebase_core/firebase_core.dart';
    import 'package:firebase_auth/firebase_auth.dart';
    import 'package:cached_network_image/cached_network_image.dart';
    

    在主函数中你需要这段代码。

    void main() async {
      WidgetsFlutterBinding.ensureInitialized();
      await Firebase.initializeApp();
      UserCredential userCredential = await FirebaseAuth.instance
          .signInAnonymously(); // you need to indentify your user
      print(userCredential);
      runApp(MyApp());
    }
    

    您可以使用此代码加载图像。

    FutureBuilder<dynamic>(
      future: FirebaseStorage().ref('google_sigin_button.png').getDownloadURL(),
      builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot) {
        if (snapshot.connectionState != ConnectionState.waiting) {
        return Image(
          image: CachedNetworkImageProvider(snapshot.data.toString()),
          fit: BoxFit.cover,
          );
        } else {
          return Text('Loading image....');
        }
      },
    ),
    

    如果您需要更多信息,这实际上是如何工作的,您应该查看我的 github 存储库,在那里您可以找到一个示例。 https://github.com/orosiferenc3/Flutter_Firebase_Storage_connection

    【讨论】:

      猜你喜欢
      • 2022-08-10
      • 2020-04-26
      • 1970-01-01
      • 1970-01-01
      • 2021-07-17
      • 1970-01-01
      • 2021-01-08
      • 2020-02-06
      • 2023-03-29
      相关资源
      最近更新 更多