Home > Mobile >  IF & ELSE FOR FLUTTER | WORKING PRINCIPLE OF FLUTTER & DART
IF & ELSE FOR FLUTTER | WORKING PRINCIPLE OF FLUTTER & DART

Time:12-05

I just started learning to code with Flutter & Dart. I could not fully understand the working principle of Flutter. There are no errors on the code I shared below. But I am not getting the result I want. On the code, the counter starts from 0. And there is a text on the counter that shows whether this counter is even or odd. This is done when the button is clicked. But the button only works once. The counter increases but the text does not change.

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  final String title;

  const MyHomePage({
    Key? key,
    required this.title,
  }) : super(key: key);

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

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;
  String evenNumber = "Even Number";
  String oddNumber = "Odd Number";

  void _incrementCounter() {
    setState(() {
      _counter  ;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(_counter / 2 == 0 ? evenNumber : oddNumber),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ),
    );
  }
}

CodePudding user response:

Change this line:

_counter / 2 == 0 ? evenNumber : oddNumber

To:

_counter % 2 == 0 ? evenNumber : oddNumber

The '%' operator evaluates the remainder that you need. Not the half (_counter/2) of counter value.

CodePudding user response:

You do not get your desired result because you are using using the normal division instead of modulo. With / you only check if the result is 0 and with % you can check if the number is even. To fix this change your Text widget to the following.

Text(_counter % 2 == 0 ? evenNumber : oddNumber),

Your full code should look like this now.

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  final String title;

  const MyHomePage({
    Key? key,
    required this.title,
  }) : super(key: key);

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

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;
  String evenNumber = "Even Number";
  String oddNumber = "Odd Number";

  void _incrementCounter() {
    setState(() {
      _counter  ;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(_counter / 2 == 0 ? evenNumber : oddNumber),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ),
    );
  }
}

CodePudding user response:

Yes, I normally used the % operator from the if block like this one below, but I could not understand that the error was from the operator, since I guess it was from the code block. So why can't I get the result I want in such a use?

     class _MyHomePageState extends State<MyHomePage> {
       int _counter = 0;
        String evenNumber = "Even Number";
          String oddNumber = "Odd Number";

        void _incrementCounter() {
          setState(() {
         _counter  ;
  
        if (_counter % 2 == 0){
         evenNumber = evenNumber;
          } else {
            evenNumber = oddNumber;
            }
            });
            }

              @override
          Widget build(BuildContext context) {
           return Scaffold(
            appBar: AppBar(
       title: Text(widget.title),
        ),
            body: Center(
            child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
              children: [
             Text(evenNumber),
  • Related