List Widgets

Jun's Coding Journey·2023년 9월 2일
0

[Learn] Flutter

목록 보기
11/22

ListTile


ListTile widget provides a consistent layout for a title, optional subtitle, leading and trailing widgets, and an onTap callback. Its primary purpose is to make it easy to build individual rows that follow Material Design guidelines without having to manually handle all the styling and layout.

ListTile(
  leading: Icon(Icons.star),
  title: Text('ListTile Title'),
  subtitle: Text('Subtitle goes here'),
  trailing: Icon(Icons.arrow_forward),
  onTap: () {
    // Handle tap.
  },
)

 

RichText


RichText widget allows you to display a paragraph of mixed-style text. With RichText, you can style a part of the text differently from the rest, which is very useful when you need to highlight specific parts or apply custom styling on certain segments of your text.

RichText works with the TextSpan widget, which represents the individual styled pieces of text. A TextSpan can contain children, which are also TextSpan widgets, allowing for a nested tree of styled text pieces.

RichText(
  text: TextSpan(
    text: 'This is ',
    style: DefaultTextStyle.of(context).style,  // Uses the default text style.
    children: <TextSpan>[
      TextSpan(text: 'bold', style: TextStyle(fontWeight: FontWeight.bold)),
      TextSpan(text: ' and '),
      TextSpan(text: 'italic', style: TextStyle(fontStyle: FontStyle.italic)),
    ],
  ),
)

 

Dismissable


Dismissible widget provides a way to create swipe-to-dismiss functionality for items in a list. When wrapped around another widget, you can swipe the Dismissible in either the horizontal or vertical direction (though horizontal is more common) to trigger an action, typically to remove the item.

It's most commonly used in ListView to allow users to dismiss individual items by swiping them left or right.

Dismissible(
  key: Key(itemID),  // A unique identifier for the item. This is crucial for Dismissible to work correctly.
  background: Container(color: Colors.red),  // The background when the item is swiped.
  onDismissed: (direction) {
    // Handle the dismissed action. Usually, this is where you'd remove the item from your data source.
    setState(() {
      items.removeAt(itemIndex);
    });
  },
  child: ListTile(title: Text('Item $itemID')),
)

 

Rotation Transition


RotationTransition widget in Flutter is a widget that applies a rotation to its child. Specifically, it's an animation widget that can smoothly rotate its child over a given turns value, which is typically a fraction between 0 and 1, but can exceed these values for multiple rotations.

This widget requires an AnimationController to control the rotation animation. The turns property takes an Animation double as its value, which is often linked to the AnimationController.

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> with SingleTickerProviderStateMixin {
  late AnimationController _controller;

  
  void initState() {
    super.initState();
    _controller = AnimationController(
      duration: const Duration(seconds: 5),
      vsync: this,
    )..repeat();  // This will make the animation repeat indefinitely.
  }

  
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('Rotation Transition Example')),
        body: Center(
          child: RotationTransition(
            turns: _controller, // linking the AnimationController
            child: Icon(Icons.refresh, size: 100),
          ),
        ),
      ),
    );
  }

  
  void dispose() {
    _controller.dispose();  // Important to dispose of the AnimationController
    super.dispose();
  }
}

 

Slide Transition


SlideTransition widget is used to animate a widget's position from an offset. It's a way to create a sliding effect for widgets, moving them in and out of view or to a specific position on the screen.

The SlideTransition requires an Animation Offset to describe the slide direction and distance. This is typically created using an AnimationController combined with a Tween Offset.

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> with SingleTickerProviderStateMixin {
  late AnimationController _controller;
  late Animation<Offset> _animation;

  
  void initState() {
    super.initState();
    _controller = AnimationController(
      duration: const Duration(seconds: 2),
      vsync: this,
    );

    _animation = Tween<Offset>(
      begin: Offset(0, -1.0), // Start position (above the top edge of the screen)
      end: Offset(0, 0),     // End position (original position)
    ).animate(_controller);

    _controller.forward();  // Start the animation
  }

  
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('Slide Transition Example')),
        body: Center(
          child: SlideTransition(
            position: _animation,
            child: Container(
              height: 100,
              width: 100,
              color: Colors.blue,
            ),
          ),
        ),
      ),
    );
  }

  
  void dispose() {
    _controller.dispose();
    super.dispose();
  }
}

 

Animated Modal Barrier


AnimatedModalBarrier widget represents a barrier that prevents user interaction with widgets located behind itself. This is commonly seen when you have a modal dialog or a bottom sheet pop up — the screen behind these elements often becomes darkened and unresponsive, which is an indication that the user needs to interact with the front element before they can interact with the rest of the application.

The "animated" part of AnimatedModalBarrier refers to its ability to animate its color. For example, when showing a dialog, you might want to animate the background color from transparent to a semi-transparent black, indicating a modal state.

Stack(
  children: <Widget>[
    Center(child: Text('This is the main content.')),
    AnimatedModalBarrier(
      color: ColorTween(begin: Colors.transparent, end: Colors.black.withOpacity(0.7)).animate(CurvedAnimation(
        parent: _animationController,
        curve: Curves.easeInOut,
      )),
      dismissible: false, // Determines whether tapping on the barrier will dismiss it.
    ),
  ],
)

 

Animated List


AnimatedList widget is a scrollable list that animates items when they are inserted or removed. It works closely with an AnimatedListState, which lets you initiate animations on the list, like adding or removing items. The AnimatedList widget requires you to specify an itemBuilder function that produces list items with an animation.

class MyAnimatedList extends StatefulWidget {
  
  _MyAnimatedListState createState() => _MyAnimatedListState();
}

class _MyAnimatedListState extends State<MyAnimatedList> {
  final GlobalKey<AnimatedListState> _listKey = GlobalKey();
  List<String> _items = ["Item 1", "Item 2", "Item 3"];

  
  Widget build(BuildContext context) {
    return Scaffold(
      body: AnimatedList(
        key: _listKey,
        initialItemCount: _items.length,
        itemBuilder: (context, index, animation) {
          return SlideTransition(
            position: animation.drive(Tween<Offset>(
              begin: Offset(1, 0),
              end: Offset(0, 0),
            )),
            child: ListTile(
              title: Text(_items[index]),
              trailing: IconButton(
                icon: Icon(Icons.delete),
                onPressed: () {
                  String removedItem = _items.removeAt(index);
                  AnimatedList.of(context).removeItem(
                    index,
                    (context, animation) => _buildItem(removedItem, animation),
                  );
                },
              ),
            ),
          );
        },
      ),
      floatingActionButton: FloatingActionButton(
        child: Icon(Icons.add),
        onPressed: () {
          _items.insert(0, "New Item");
          _listKey.currentState!.insertItem(0);
        },
      ),
    );
  }

  Widget _buildItem(String item, Animation<double> animation) {
    return SlideTransition(
      position: animation.drive(Tween<Offset>(
        begin: Offset(1, 0),
        end: Offset(0, 0),
      )),
      child: ListTile(title: Text(item)),
    );
  }
}

 

List Wheel Scroll View


ListWheelScrollView is a widget that arranges its children in a circle and scrolls them along the main axis. The primary visual difference between ListView and ListWheelScrollView is the way the items appear and scroll: ListWheelScrollView makes its items appear as though they are on a wheel or a cylinder. The items in the middle of the viewport are rendered at their full size, but as they move towards the edges, they shrink and fade out.

ListWheelScrollView(
  itemExtent: 50.0,
  diameterRatio: 1.5,
  magnification: 1.2,
  useMagnifier: true,
  children: List<Widget>.generate(
    10,
    (index) => Center(child: Text('Item $index')),
  ),
)

 

About List Tile


AboutListTile widget in Flutter is a convenient widget designed to show an about dialog. When tapped, this list tile displays an about box, which provides information about the app, such as its name, version, description, and other customizable attributes. The AboutListTile is typically used in the app's settings or navigation drawer.

The widget makes it easy to adhere to platform conventions related to displaying app-related information, without having to design a custom interface.

AboutListTile(
  icon: Icon(Icons.info),
  applicationName: "MyApp",
  applicationVersion: "1.0.0",
  applicationIcon: Icon(Icons.app_registration),
  applicationLegalese: '© 2023 MyApp Inc.',
  aboutBoxChildren: <Widget>[
    Text("Thank you for using our application!"),
  ],
)

 

Checkbox List Tile


CheckboxListTile is a ListTile-like widget that combines the functionalities of a Checkbox and a ListTile. It provides an easy way to create a list item with a checkbox, where the checkbox can be placed at the start or end of the item.

The CheckboxListTile is often used in settings or preference lists, where users can toggle on or off specific options.

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'CheckboxListTile Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  bool _isChecked = false;

  
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('CheckboxListTile Demo'),
      ),
      body: ListView(
        children: <Widget>[
          CheckboxListTile(
            title: Text('Enable Notifications'),
            value: _isChecked,
            onChanged: (bool value) {
              setState(() {
                _isChecked = value;
              });
            },
            secondary: const Icon(Icons.notifications_active),
          ),
          // ... Add more CheckboxListTile widgets as needed
        ],
      ),
    );
  }
}

 

Switch List Tile


SwitchListTile widget combines a Switch widget with a ListTile. This widget provides a way to create a list item with an interactive switch. It is similar in use and purpose to CheckboxListTile, but instead of a checkbox, it offers a switch, which is a common UI element for toggling between two states, typically "on" and "off".

You can also use SwitchListTile.adaptive to automatically implement style depending on Android or iOS device (no need to manually set style for "Cupertino" or default android).

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'SwitchListTile Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  bool _isSwitched = false;

  
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('SwitchListTile Demo'),
      ),
      body: ListView(
        children: <Widget>[
          SwitchListTile(
            title: Text('Wi-Fi'),
            value: _isSwitched,
            onChanged: (bool value) {
              setState(() {
                _isSwitched = value;
              });
            },
            secondary: const Icon(Icons.wifi),
          ),
          // ... Add more SwitchListTile widgets as needed
        ],
      ),
    );
  }
}

profile
Greatness From Small Beginnings

0개의 댓글