In this example, we are going to show you how to implement widget order like z-index on CSS in Flutter. Z-index is a very important factor to implement the order of widgets according to which widgets we want to show on top of one another.
First, Add an Indexed package in your dependency by adding the following lines in pubspec.yaml file:
dependencies:
flutter:
sdk: flutter
indexed: ^0.0.8
Indexer(
children: [
Indexed(
index: 3, //more the index, upper the order
child: Positioned(
top: 50, left: 50,
child: Container(
height: 100, width: 100,
color: Colors.redAccent,
),
),
),
Indexed(
index: 1, //less the value, below the order
child: Positioned(
top: 100, left: 100,
child: Container(
height: 100, width: 100,
color: Colors.blueAccent,
),
),
),
Indexed(
index: 2, //last at widget tree, but middle in order
child: Positioned(
top: 90, left: 30,
child: Container(
height: 100, width: 100,
color: Colors.purple,
),
),
)
],
)
Place the Indexed() widget inside Indexer() provided by Indexed Package and implement the index value to Indexed() widget. Higher the value, upper the order, the order of the widget tree doesn't matter.
import 'package:flutter/material.dart';
import 'package:indexed/indexed.dart';
void main(){
runApp(MyApp());
}
class MyApp extends StatelessWidget{
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Home(),
);
}
}
class Home extends StatefulWidget{
@override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
List<int> nums = [1,2,3,4,5,6,7,8,9,10];
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Z-index in Flutter"),
backgroundColor: Colors.redAccent
),
body: Container(
child: Indexer(
children: [
Indexed(
index: 3, //more the index, upper the order
child: Positioned(
top: 50, left: 50,
child: Container(
height: 100, width: 100,
color: Colors.redAccent,
),
),
),
Indexed(
index: 1, //less the value, below the order
child: Positioned(
top: 100, left: 100,
child: Container(
height: 100, width: 100,
color: Colors.blueAccent,
),
),
),
Indexed(
index: 2, //last at widget tree, but middle in order
child: Positioned(
top: 90, left: 30,
child: Container(
height: 100, width: 100,
color: Colors.purple,
),
),
)
],
),
)
);
}
}
In this way, you can apply z-index widget order in Flutter.
Please Wait...
No any Comments on this Article