Home > Software design >  Dart: Reading a specific line in a text based on a keyword
Dart: Reading a specific line in a text based on a keyword

Time:08-19

I have this line of text that is as follows:

IMEI
IMEII :869425035089513
IME12:869425035100520
SN:3ST0218A22000432

I want to only get the 2nd line of text that is "IMEII :869425035089513" but remove the rest. How shall I do that in Dart?

CodePudding user response:

try this

var str = "IMEI"
      IMEII :869425035089513
      IME12:869425035100520
      SN:3ST0218A22000432";
  var parts = str.split('\n');
  print(parts[0]);
  print(parts[1]);// print 2nd Line data

CodePudding user response:

When you enter a string in the text field, only the strings that contain the entered string are displayed.

import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Home(),
    );
  }
}

class Home extends StatefulWidget {
  const Home({Key? key}) : super(key: key);

  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {
  //data
  List<String> _list = [
    'IMEI',
    'IMEII :869425035089513',
    'IME12:869425035100520',
    'SN:3ST0218A22000432'
  ];

  //show data
  List<String> _data = [];

  @override
  Widget build(BuildContext context) {
    Size _size = MediaQuery.of(context).size;
    
    return Scaffold(
      body: SafeArea(
        child: SingleChildScrollView(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              _textFiled(_size),
              for (int i = 0; i < _data.length; i  )
                _showData(_size, i),
            ],
          ),
        ),
      ),
    );
  }

  //TextFiled Widget
  Widget _textFiled(Size size) {
    return Container(
      width: size.width,
      height: size.height * 0.1,
      child: TextField(
        decoration: InputDecoration(
          labelText: 'Text',
        ),
        onChanged: (String text) {
          _data.clear();
          setState(() {
            if (text.isEmpty) {
              _data = _list.toList();
            } else {
              for (int i = 0; i < _list.length; i  ) {
                if (_list[i].contains(text)) {
                  _data.add(_list[i].toString());
                }
              }
            }
          });
        },
      ),
    );
  }

  //show Data
  Widget _showData(Size size, int index) {
    return Container(
      width: size.width,
      height: size.height * 0.05,
      child: Text('${_data[index]}'),
    );
  }
}

You can use contain() which is a string comparison.

  • Related