How to add image in Flutter

前端 未结 8 1951
渐次进展
渐次进展 2020-12-01 01:10

I am developing Flutter app for the first time.. I have an issue in adding a image. I have a below questions :

  1. Where to create images folder?
  2. Where to
8条回答
  •  一向
    一向 (楼主)
    2020-12-01 01:44

    An alternative way to put images in your app (for me it just worked that way):

    1 - Create an assets/images folder

    2 - Add your image to the new folder

    3 - Register the assets folder in pubspec.yaml

    4 - Use this code:

    import 'package:flutter/material.dart';
    
    void main() => runApp(MyApp());
    
    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
    
        var assetsImage = new AssetImage('assets/images/mountain.jpg'); //<- Creates an object that fetches an image.
        var image = new Image(image: assetsImage, fit: BoxFit.cover); //<- Creates a widget that displays an image.
    
        return MaterialApp(
          home: Scaffold(
            appBar: AppBar(
              title: Text("Climb your mountain!"),
              backgroundColor: Colors.amber[600], //<- background color to combine with the picture :-)
            ),
            body: Container(child: image), //<- place where the image appears
          ),
        );
      }
    }
    

提交回复
热议问题