Posts in category “Programming”

Adding Auto-Focus to TextFields in Flutter

When building user interfaces in Flutter, it's often desirable to have the keyboard automatically pop up and focus set on a specific TextField when navigating to a new page or rendering a widget. This auto-focus feature can greatly improve the user experience by allowing users to start typing immediately without having to manually tap on the TextField to focus it.

In this blog post, we'll explore how to implement the auto-focus feature for TextFields in Flutter using FocusNodes.

Step 1: Create a FocusNode

The first step is to create a FocusNode instance, which represents the focus state of a particular widget. You can create a FocusNode in the initState method of your StatefulWidget:

late FocusNode myFocusNode;

@override
void initState() {
  super.initState();
  myFocusNode = FocusNode();
}

Step 2: Associate the FocusNode with the TextField

Next, you need to associate the FocusNode with the TextField you want to focus. You can do this by passing the FocusNode to the focusNode property of the TextField:

TextField(
  focusNode: myFocusNode,
  // other properties
)

Step 3: Request Focus on the FocusNode

To set the focus on the TextField, you need to request focus on the FocusNode. The best place to do this is after the widget has been rendered, which you can achieve using the WidgetsBinding.instance.addPostFrameCallback method:

@override
void initState() {
  super.initState();
  myFocusNode = FocusNode();
  WidgetsBinding.instance.addPostFrameCallback((_) {
    myFocusNode.requestFocus();
  });
}

The addPostFrameCallback method ensures that the focus request is made after the widget has been rendered, which is necessary to avoid any potential issues with focus management.

Example Implementation

Here's an example implementation of a StatefulWidget that demonstrates the auto-focus feature for a TextField:

class NewNoteState extends State<NewNote> {
  final TextEditingController _noteController = TextEditingController();
  final FocusNode _noteFocusNode = FocusNode();

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _noteFocusNode.requestFocus();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('New Note'),
      ),
      body: Column(
        children: [
          TextField(
            controller: _noteController,
            focusNode: _noteFocusNode,
            keyboardType: TextInputType.multiline,
            // other properties
          ),
          // other widgets
        ],
      ),
    );
  }

  @override
  void dispose() {
    _noteController.dispose();
    _noteFocusNode.dispose();
    super.dispose();
  }
}

In this example, we create a FocusNode called _noteFocusNode and associate it with the TextField. In the initState method, we use WidgetsBinding.instance.addPostFrameCallback to request focus on the _noteFocusNode after the widget has been rendered. This will automatically set the focus on the TextField when the NewNote widget is rendered.

Conclusion

Adding the auto-focus feature to TextFields in Flutter can greatly enhance the user experience by allowing users to start typing immediately without having to manually tap on the TextField to focus it. By creating a FocusNode, associating it with the TextField, and requesting focus on the FocusNode after the widget has been rendered, you can easily implement this feature in your Flutter applications.

Remember to dispose of the FocusNode when it's no longer needed to avoid memory leaks. Additionally, be mindful of potential issues with focus management and use the appropriate methods and callbacks to ensure smooth focus handling in your application.

Handling Back Navigation with PopScope in Flutter

Building Flutter apps? You'll likely face situations where you need to control the back button. Imagine a user editing a note, and you want a confirmation dialog before they accidentally ditch their work!

The old WillPopScope widget used to handle this, but it's deprecated as of Flutter 3.12 (thanks, Android 14's new back gesture!). The new sheriff in town is PopScope, but it doesn't quite let you block the back action directly.

After a couple hours of researching and investigating, Here's the solution to get PopScope to mimic WillPopScope:

  @override
  Widget build(BuildContext context) {
    return PopScope(
      canPop: false,
      onPopInvokedWithResult: (bool didPop, object? result) async {
        if (!didPop) {
          final navigator = Navigator.of(context);
          if (_noteController.text.isEmpty || (_noteController.text.isNotEmpty && (await _showUnsavedChangesDialog(context) ?? false))) {
            navigator.pop();
          }
        }
      },
      child: Scaffold(
      ...

and the following shows the difference:

   @override
   Widget build(BuildContext context) {
-    return WillPopScope(
-      onWillPop: () async {
-        if (_noteController.text.isNotEmpty) {
+    return PopScope(
+      canPop: false,
+      onPopInvokedWithResult: (bool didPop, object? result) async {
+        if (!didPop) {
+          final navigator = Navigator.of(context);
+          if (_noteController.text.isEmpty || (_noteController.text.isNotEmpty && (await _showUnsavedChangesDialog(context) ?? false))) {
+            navigator.pop();
+          }
-           final shouldPop = await _showUnsavedChangesDialog(context);
-          return shouldPop ?? false;
         }
-        return true;
       },
       child: Scaffold(

Here's how this solution works:

  1. canPop is set to false, disabling the system back gesture.
  2. In the onPopInvokedWithResult callback, it checks if didPop is false (indicating that the pop operation hasn't occurred yet)
  3. Then, it checks if there aren't any unsaved changes _noteController.text.isEmpty, or, although there are unsaved changes (_noteController.text.isNotEmpty), the user answers Yes when asking confirmation.
  4. If any of the conditions are true, it manually triggers the pop operation by calling navigator.pop(). Otherwise, do nothing.

By disabling the system back gesture (canPop: false) and manually triggering the pop operation (navigator.pop()), this solution allows you to perform necessary actions (e.g., showing a confirmation dialog) before the pop operation occurs, effectively replicating the behavior of WillPopScope.

I hope it helps!

Moq Tips 2 - check if a log message with a specific prefix/suffix and call a method with an object having a specific field value

  1. To check if a log message with a specific prefix is logged, you can use Moq's Verify method along with an appropriate assertion.
_logger.Verify(logger => logger.logInformation(
    It.Is<string>(s => s.StartsWith("specific prefix"))), Times.Once);
  1. To verify that a method is called with an object containing a specific property value, you can use Moq's It.Is<T> matcher along with a lambda expression. Here's an example:
_mockObject.Verify(x => x.MyMethod(It.Is<MyObject>(
    obj => obj.PropertyValue == expectedPropertyValue)), Times.Once);
  1. Correctly returns null: Sometimes we need to set up a Moq mock to return null but cannot directly do it as Moq doesn't allow. Please check the following way that you should use:
_bookStoreAccountRepository.Setup(
    b => b.GetBookStoreAccountByUserName(It.IsAny<string>()))
    .Returns((BookStoreAccount)null);

The key is to use (BookStoreAccount)null to explicitly cast null to the expected return type.

Moq tips 1 - learn how to write unit tests from ChatGPT

When should I use mockObject.Reset() and when should I use mockObject.Invocations.Clear()?

In the context of using a mocking framework like Moq in C# for unit testing, the choice between mockObject.Reset() and mockObject.Invocations.Clear() depends on what you want to achieve.

  1. mockObject.Reset():

    • This is specific to the Moq library.
    • It resets the mock object, removing any setups or custom behavior you might have defined for that mock.
    • It does not clear recorded invocations; you can still access them after calling Reset().

    Example:

    var mock = new Mock<MyClass>();
    mock.Setup(x => x.MyMethod()).Returns("Original");
    
    // ... code using the mock ...
    
    // Reset the mock, removing setups
    mock.Reset();
    
    // Now, if you call the method, it won't use the previous setup
    var result = mock.Object.MyMethod();
    
  2. mockObject.Invocations.Clear():

    • This clears the recorded invocations on the mock object.
    • It doesn't affect setups or custom behavior. It just removes the history of invocations.
    • This can be useful when you want to verify interactions or check the number of invocations without interference from previous test runs.

    Example:

   var mock = new Mock<MyClass>();
   mock.Setup(x => x.MyMethod()).Returns("Original");
   
   // ... code using the mock ...
   
   // Clear recorded invocations
   mock.Invocations.Clear();
   
   // Now, if you verify invocations, it won't consider previous calls
   mock.Verify(x => x.MyMethod(), Times.Never());

In summary:

  • Use mockObject.Reset() when you want to clear setups and start fresh with the mock.
  • Use mockObject.Invocations.Clear() when you want to clear the history of invocations, but keep the existing setups and behaviors.

If I set up a method with the same parameters multiple times, the last setup will take effect, right?

In most mocking frameworks, including Moq for C#, the answer is YES. Each new setup for the same method and parameters overrides any previous setups.

Here's an example using Moq:


// Setting up the method with the same parameters but different returns
mock.Setup(x => x.MyMethod()).Returns("FirstSetup");
mock.Setup(x => x.MyMethod()).Returns("SecondSetup");

// Now, if you call the method, it will return "SecondSetup"
var result = mock.Object.MyMethod();

A neat way to remove trailing zeros from a decimal number in C#

We can get unexpected trailing zeros when we serialzie an object with decimal properties, normally it will not hurt. However, it does hurt when we want to compare two objects by serializing them to JSON string. I tried a few solutions and finally find the following one is the best.

public static decimal Normalize(this decimal value)
{
    return value/1.000000000000000000000000000000000m;
}

Reference