How to add an image without using assets in flutter

This Article is posted by abbas.devcode at 3/28/2020 11:37:35 AM



<p>In this tutorial, we are going to have a look at adding or displaying an image from stored on the device without adding it to assets. For this purpose, we are going to make use of the **file_picker package. **</p> <p>Let's have a look at the tiny illustration of how it looks before writing the code.</p> <p>![](../../../Uploads/2e97d578-356f-4455-9b57-46c20c3aa1e2.gifwidth="50%height="auto](</p> <p><strong>STEPS TO FOLLOW:</strong></p> <p>**1. **Add the package dependency to your pubspec.yaml file as follows</p> <p>**2. **Use the following code inside your <strong>main.dart file</strong>.</p> <p>runApp(MyApp());</p> <p>class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'Image Picker Demo', theme: ThemeData( primarySwatch: Colors.blue, ), home: MyHomePage(title: 'Image Picker Demo'), debugShowCheckedModeBanner: false, ); } }</p> <p>class MyHomePage extends StatefulWidget { MyHomePage({Key key, this.title}) : super(key: key);</p> <p>final String title;</p> <p>@override _MyHomePageState createState() => _MyHomePageState(); }</p> <p>class _MyHomePageState extends State { File imageFile;</p> <p imageFile="file;">_loadImage() async { File file = await FilePicker.getFile(); setState(() ); }</p> <p>@override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(widget.title), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Container( height: 250, width: 320, decoration: BoxDecoration( border: Border.all( width: 1, ), ), margin: EdgeInsets.all(16.0), child: imageFile == null ? Center( child: Text( 'Click the Floating Action Button to Add Image', textAlign: TextAlign.center, ), ) : Image.file( imageFile, fit: BoxFit.contain, )) ], ), ), floatingActionButton: FloatingActionButton( onPressed: _loadImage, tooltip: 'Load Image', child: Icon(Icons.add), ), ); } }</p> <p>**Quick Overview: **</p> <ul> <li><p>FilePicker package offers an <strong>asynchronous</strong> method getFile() which returns the file selected from the local storage.</p> </li> <li><p>You can also restrict the files loaded on the basis of file types and file extensions by providing them as arguments inside the getFile() method.</p> </li> <li><p>It also offers other methods such as getFilePath() which returns the path of the file stored locally.</p> </li> <li><p>Alongside, it also has methods to select multiple files at once namely getMultiFile() and getMultipleFilePath().</p> </li> </ul> <p>If you have any questions, do ask them in the comments section. Keep Fluttering :)</p>


Tags: adding file without using assets from local storage








0 Comments
Login to comment.
Recent Comments