Flutter creates a sample application with a stateful widget in a new Flutter project
A basic application can be created with a stateless widget
Provided example renders a basic stateless widget which displays a local image
Check Flutter installation to setup Flutter
Use flutter create
command to create a Flutter project (here nc_app) :
flutter create nc_app
Running this command creates a sample flutter application with a button and text which displays the number of times the button is pressed
Setup for using assets in a Flutter application includes copying the assets to Flutter project directory and then adding its path to pubspec.yaml
Create a directory image_assets inside project directory (it can also be some other name)
Copy following image (or some other image) to image_assets directory
pubspec.yaml
Open pubspec.yaml in a code editor or text editor
Uncomment and align the line containing # assets:
Add the created directory (or path to asset) after the uncommented line as:
uses-material-design: true
# To add assets to your application, add an assets section, like this:
# assets:
assets:
- image_assets/
# - images/a_dot_burr.jpeg
Since it is a directory it is followed by a /
(slash character)
Open lib/main.dart in a code editor or text editor
Delete whole code from lib/main.dart
Replace with the following code
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: AlertWidget()
)
)
);
}
}
class AlertWidget extends StatelessWidget {
//path of added image is assigned
String imagePath = "image_assets/flutterpic.jpg";
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title:
Center(child: Text('Nc Basic App', textAlign: TextAlign.center)),
),
body: Container(
width: double.infinity,
// a DecoratedBox allows an image to be set as background for its child widget
child: DecoratedBox(
decoration: BoxDecoration(
// path is passed as argument to AssetImage widget
image: DecorationImage(image: AssetImage(imagePath), fit: BoxFit.cover),
),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
SizedBox(height:10.0),
Text('Basic App in Flutter',
style: TextStyle(color: Colors.white, fontSize: 25)),
Text('with an Image ',
style: TextStyle(color: Colors.white, fontSize: 25))
],
),
),
),
);
}
}
Ensure one of following device is connected/started
Go to project directory (here nc_app)
Use flutter run
command to run
flutter run
It builds and runs app on an available android/ios device